c# Writing Increasing Numbers in a While to a Database - c#

Im trying to write "Increasing Numbers/Price" in a While with incrementing in my Database, but still didnt work...
Without a while /incrementing my other code works very well, and i get writed data in my database but with the "while code" not... can anyone help me out? thx you
namespace Testing
{
class Program
{
static void Main(string[] args)
{
SqlConnection con;
string str;
string Buyable;
Buyable = "0";
int count = 10;
double Add = 0.00000000;
for (int i = 0; i < count; i++)
{
Add = Add + 0.00000005;
try
{
str = #"..........";
con = new SqlConnection(str);
con.Open();
Console.WriteLine("Database connected");
string query = "INSERT INTO[dbo].[Table]([Price], [Buyable]) VALUES('" + Add + "'," + Buyable + ")";
SqlCommand ins = new SqlCommand(query, con);
ins.ExecuteNonQuery();
Console.WriteLine("Stored");
Console.ReadKey();
}
catch (SqlException)
{
}
}
}
}
}

Try this:
static void Main(string[] args)
{
double Add = 0D; //You really should use a **decimal** for anything to do with money!
int Buyable = 0;
int count = 10;
string str = #"..........";
string sql = "INSERT INTO[dbo].[Table]([Price], [Buyable]) VALUES(#Add, #Buyable);"; // + Add + "'," + Buyable + ")";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand ins = new SqlCommand(sql, con))
{
ins.Parameters.Add("#Add", SqlDbType.Float);
ins.Parameters.Add("#Buyable", SqlDbType.Int); //guessing at parameter type here
con.Open();
Console.WriteLine("Database connected");
for (int i = 0; i < count; i++)
{
Add += 0.00000005D;
try
{
ins.Parameters["#Add"].Value = Add;
ins.Parameters["#Buyable"].Value = Buyable;
ins.ExecuteNonQuery();
Console.WriteLine("Stored");
Console.ReadKey();
}
catch (SqlException ex)
{
//Do *something* with the exception here!
Console.WriteLine("Error using the database. The message is:\n{0}", ex.Message);
}
}
}
}

Don't leave the connection open and try to use using with all disposable objects in your C# life.
str = #"..........";
using(con = new SqlConnection(str))
{
con.Open();
Console.WriteLine("Database connected");
string query = "INSERT INTO[dbo].[Table]([Price], [Buyable]) VALUES('" + Add + "'," + Buyable + ")";
SqlCommand ins = new SqlCommand(query, con);
ins.ExecuteNonQuery();
Console.WriteLine("Stored");
Console.ReadKey();
}

Here you are writing con.Open(); in loop without closing previous connection con.Close(); which cause to throw error , write con.Close(); after ins.ExecuteNonQuery(); and try.
Another solution is Open your connection before loop and close after for loop ends .. I think this may help you

Related

Conversion failed when converting from a character string to uniqueidentifier when inserting value to sql

I have simple SQL table called test which has two column.first column is an TINYINT and second one is a type of UNIQUEIDENTIFIER.
I have created simple method to insert values into "test" table using for loop and its working fine without any errors.But once i try to create string to uniqueidentifier conversion error it will roll back the transaction and delete all previous inserted values in same transaction.
This is the place where conversion happen
strCommand += "INSERT INTO Test(Test, Test2) VALUES(" + i.ToString() + ", '" + (i == 251 ? Guid.NewGuid().ToString().Remove(12, 1) : Guid.NewGuid().ToString()) + "'); ";
Here is the my complete code
private static string TryThisPlease()
{
SqlConnection connection = null;
SqlCommand command = null;
SqlTransaction transaction = null;
string strRet = "OK";
try
{
connection = new SqlConnection(connectionString);
connection.Open();
//starting transaction mode
transaction = connection.BeginTransaction(IsolationLevel.Snapshot);
command = new SqlCommand("Test", connection);
command.CommandType = CommandType.Text;
command.Transaction = transaction;
//for (int i = 255; i < 257; i++)
for (int i = 250; i < 255; i++)
{
string[] strData = new string[] { "", "3" };
string strCommand = "";
//strCommand += "INSERT INTO Test(Test, Test2) VALUES(" + i.ToString() + ", '" + Guid.NewGuid().ToString() + "'); ";
strCommand += "INSERT INTO Test(Test, Test2) VALUES(" + i.ToString() + ", '" + (i == 251 ? Guid.NewGuid().ToString().Remove(12, 1) : Guid.NewGuid().ToString()) + "'); ";
command.CommandText = strCommand;
if (command.Connection.State != ConnectionState.Open)
command.Connection.Open();
try
{
command.ExecuteNonQuery();
}
catch (Exception EX)
{
strRet = "FAIL";
try
{
}
catch (Exception)
{
strRet = "FAIL";
}
}
}
transaction.Commit();
}
catch (Exception EX)
{
transaction.Rollback();
strRet = "FAIL";
}
finally
{
connection.Close();
}
return strRet;
}
Uncommenting the two lines commented and commenting out lines below,another error with same severity happens. Transactions are not rolled back in this scenario
Is there any way to prevent the transaction being rollback or did i miss something in my code ?
if you want previous inserts to be successful, what you have to do is, create and commit the transaction inside the foreach loop, so that each row is considered separate transaction.
using(SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
for (int i = 250; i < 255; i++) {
using(SqlCommand command = new SqlCommand("", connection, trans)) {
command.CommandType = System.Data.CommandType.Text;
using(SqlTransaction trans = connection.BeginTransaction()) {
try {
strCommand = "INSERT INTO Test(Test, Test2) VALUES(" + i.ToString() + ", '" + (i == 251 ? Guid.NewGuid().ToString().Remove(12, 1) : Guid.NewGuid().ToString()) + "'); ";
command.CommandText = strCommand;
command.ExecuteNonQuery();
trans.Commit();
}
catch(Exception e) {
//Handle Error
trans.Rollback();
}
}
}
}
}
But, your command is prone for sql injection attacks. I would suggest you to parametrize the query as given below:
SqlCommand cmd = new SqlCommand(
"INSERT INTO Test(Test, Test2) VALUES(#id1,#id2)", conn);
cmd.Parameters.Add( new SqlParameter(#id1, SqlDbType.Int)).Value = i;
cmd.Parameters.Add( new SqlParameter(#id2, SqlDbType.Guid)).Value = (i == 251 ? Guid.NewGuid().ToString().Remove(12, 1) : Guid.NewGuid().ToString());
UPDATE
If you want to still go with batch transaction, you can consider savepoint for the transaction. Instead of rolling back the whole transaction, you can rollback till the savepoint.Read more on Savepoint
command.CommandText = strCommand;
trans.Save($"save{i}");
command.ExecuteNonQuery();
trans.Commit();
}
catch(Exception e) {
//Handle Error
trans.Rollback($"save{i}");
trans.Commit();
}
The problem lies in this statement Guid.NewGuid().ToString().Remove(12, 1). The result of this statement will remove the 12th character from your generated GUID which is not a valid GUID and hence the database insertion fails.
Guid Format:
"00000000-0000-0000-0000-000000000000"
^ 12th index character which will get removed from the Guid.
When the condition i==251 becomes true this code Guid.NewGuid().ToString().Remove(12, 1) will get executed and it will generate the error. You need to update this to produce GUID in correct format inorder to solve your issue.

c# Connection must be valid and open to commit transaction TransactionScope

I'm using Transactions on my Dao and in particular I'm using the TransactionScope object for the first time. But when I compile and start my procedure on my pc the method I wrote in will give me this error:
Connection must be valid and open to commit transaction
code:
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteReader();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
//cmd.Transaction = Transazione;
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteReader();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
You need to move scope.Complete(); within your connection using as it is being disposed before you are completing your scope. Also, change your calls to use ExecuteNonQuery as opposed to ExecuteReader, as you are opening a SqlDataReader and not disposing of it.
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
ok Ok i have inverted using connection with scope
And I opened the connection before scope and works !
I hope it is right, thank you !
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
using (TransactionScope scope = new TransactionScope())
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}

Login form with SQLite in C#

I'm having a problem making a loginform with sqlite in C#. this is the code
SQLiteConnection connectionstring;
connectionstring = " Data Source = C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db; Version = 3 ";
public void LoadData()
{
try
{
SQLiteCommand SelectCommand = new SQLiteCommand("SELECT `Username`, `Password` FROM `LoginData` WHERE `Username` = '" + flatTextBox1.Text + "' AND `Password` = '" + flatTextBox2.Text + "'", connectionstring);
SQLiteDataReader myReader;
connectionstring.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
Base bs = new Base();
bs.Show();
this.Hide();
connectionstring.Close();
}
else if (count == 0)
{
flatAlertBox1.kind = FlatUI.FlatAlertBox._Kind.Error;
flatAlertBox1.Text = "data not right";
connectionstring.Close();
}
else
{
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
connectionstring.Close();
}
}
it is showing error in this line of code
connectionstring = " Data Source = C:\\Crystal Management\\Crystal Management\bin\\Debug\\Konaku.db; Version = 3 ";
message error is : Cannot implicitly convert type 'string' to 'Finisar.SQLite.SQLiteConnection'
what can I do with this?
This is the proper way to query SQL. Always use "using" for disposable class like SQLiteConnection, SQLiteCommand, and SQLiteDataReader. Use parameterized queries to avoid sql injection.
public void LoadData()
{
try
{
using (var conn = new SQLiteConnection(#"Data Source=C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db;Version=3"))
{
conn.Open();
using (var cmd = new SQLiteCommand("SELECT Username,Password FROM LoginData WHERE Username='#username' AND Password = '#password'", conn))
{
cmd.Parameters.AddWithValue("#username", flatTextBox1.Text);
cmd.Parameters.AddWithValue("#password", flatTextBox2.Text);
using (var reader = cmd.ExecuteReader())
{
var count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
Base bs = new Base();
bs.Show();
Hide();
}
else if (count == 0)
{
flatAlertBox1.kind = FlatUI.FlatAlertBox._Kind.Error;
flatAlertBox1.Text = "data not right";
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It should be like this
sql_con = new SQLiteConnection
("Data Source=C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db;Version=3;New=False;Compress=True;");

Nothing happens on query execution

I have this simple code C# and SQL Server database:
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
// here like cursor stop
cm2.ExecuteNonQuery();
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
I have run it but nothing happens on query execution I used MessageBox like that to identify the line that has the problem
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
MessageBox.Show("1");
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
MessageBox.Show("2");
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
MessageBox.Show("3");
// here cursor stops
cm2.ExecuteNonQuery();
// that messagebox isn't shown
MessageBox.Show("4");
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
Any help will be appreciated
You haven't opened your Connection. See below.
You should also use the using syntax to make use of IDisposable
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
var sqlCmdText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
try
{
using (var sqlConnection = new SqlConnection([YOUR CONNECTION STRING HERE]))
{
using (var sqlCommand = new SqlCommand(sqlCmdText, sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new DataException(ex.Message);
}

Input string was not in a correct format in Sales Order

I am having this problem
Input string was not in a correct format.
highlighted to the part of:
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
I am having a hard time figuring out what is the error, can you help me? Thank you very much.
Here is my set codes:
private void displayNavigate()
{
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
double dTotal = 0;
try
{
for (int nRow = 0; nRow <= grdDetails.Rows.Count - 1; nRow++)
{
dTotal = dTotal + Convert.ToDouble((grdDetails.Rows[nRow].Cells["Amount"].Value.ToString()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
lblTotal.Text = string.Format("{0:#,##00.00}", dTotal);
}
//================================================================================
//================================================================================
private void DisplayOrder(int nOrderNo)
{
try
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText = "SELECT " +
"B.OrderNo, B.OrderDate, A.CustomerNo, " +
"A.CustomerName, A.CustomerAddress, B.PurchaseOrderNo, B.AgentName, B.Status " +
"FROM Customers AS A, Orders AS B " +
"WHERE A.CustomerNo = B.CustomerNo " +
"AND B.OrderNo ='" + nOrderNo + "'";
SqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
txtOrderNo.Text = dr["OrderNo"].ToString();
dtpOrderDate.Value = Convert.ToDateTime(dr["OrderDate"].ToString());
txtCustomerNo.Text = dr["CustomerNo"].ToString();
txtCustomerName.Text = dr["CustomerName"].ToString();
txtCustomerAddress.Text = dr["CustomerAddress"].ToString();
txtPONo.Text = dr["PurchaseOrderNo"].ToString();
cboAgentName.Text = dr["AgentName"].ToString();
txtOrderStatus.Text = dr["Status"].ToString();
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//================================================================================
//================================================================================
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT PackagingOutside, Quantity, Unit, ProductNo, ProductName, ProductSize, PackagingInside, " +
"SellingDiscount, SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
}
when you use Convert.ToInt16 you will get this exception if value does not consist of an optional sign followed by a sequence of digits (0 through 9)
Do a validation for inputs before proceed like below.
int orderNo;
if (int.TryParse(txtOrderNo.Text, out orderNo))
{
DisplayOrder(orderNo);
DisplayOrderDetails(orderNo);
}
Side Note :
don't share the SqlConnection create new instant when you need it and wrap it with using block like below
using (SqlConnection con = new SqlConnection(connectionString))
{
}
Use SQL Parameters
cmdSelect.CommandText = "SELECT * FROM Orders WHERE OrderNo = #OrderNo";
cmdSelect.Parameters.AddWithValue("#OrderNo", nOrderNo);
This means that the value in txtOrderNo.Text is not considered an integer. You will get this error if your textbox is empty.
Either check that the textbox contains data, or use the TryParse (http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method
There are two things to consider,
Values entered in the textbox should be an integer in the range of 16 bit, if it can be bigger value, then you have to think of going to long, int32 etc.
Validate the textbox using TryParse() which will tell you whether it has valid value entered.

Categories