Looping parameterized query - c#

I've been looking for its solution for some time now, I've seen similar questions here on SO but the answers there didn't solve my problem. In my situation, I would like to loop through the rows of datagridview values to insert it to MySql database. The number of rows in the datagridview will depend on the user. When I try to input 2 or more rows of datagridview values and try to insert it to the database, only the first row of data is inserted successfully.
Here is my code:
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
The error: Parameter '#num_Delivery' has already been defined. I'm new at using C# language. Any ideas and suggestions would be welcomed.

You can do it like this. It should work.
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
cmd.Parameter.Clear();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}

Move
MySqlCommand cmd = new MySqlCommand();
in the for loop:
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
or clear its Parameters collection:
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
Sql string can be out of loop.

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'

Im trying to insert this test data in my sql database and I'm getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'
Any ideas how to solve this?
DateTime date = DateTime.Now;
string test = "{'payload': {'businessName': 'COMPANY1', 'subscriberName': 'JOHN DOE', 'accountNumber': 'CY68005000121234567890123456', 'numberOfRecords': 1," +
"'currentBalance': 4195.5, 'transactions': [{'transactionNumber': 'TR00000000','sequenceNumber': '000','transactionCode': '305','actualDateTime': '201812041624'," +
"'transactionValueDate': '2018-12-04', 'transactionCurrencyCode': 'EUR', 'transactionAmount': -1149.5, 'balance': 4195.5, 'chequeNo': '', 'depositedBy': 'CY68005000121234567890123456'," +
"'customerReference': 'uniqueValue', 'paymentNotes': 'NOTES', 'exchangeRate': 0}]}, 'errors': null}";
trans = JsonConvert.DeserializeObject<HB_transactions>(test);
for (int i=0; i<trans.payload.transactions.Count; i++)
{
string query = "SELECT TransactionId FROM AABankTransTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dataReader = cmd.ExecuteReader();
bool exists = false;
while(dataReader.Read())
{
if(dataReader[0].ToString() == trans.payload.transactions[i].transactionNumber)
{
exists = true;
break;
}
}
dataReader.Close();
if (exists) continue;
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES ('" + trans.payload.transactions[i].transactionNumber + "', 'HB', " + args[0] + ", '" + trans.payload.transactions[i].transactionCurrencyCode + "', " +
trans.payload.transactions[i].transactionAmount + ", " + date + ", 0, '" + trans.payload.transactions[i].depositedBy + "', '" +
trans.payload.transactions[i].paymentNotes + "', " + DateTime.Parse(trans.payload.transactions[i].transactionValueDate) + ")";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
Solved by using SQL parameters instead of string concatenation.
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES (#TransID, 'HB', #COMID, #curr, #amount, #dlDate, 0, #depositor, #Details, #TransDate)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#TransID", trans.payload.transactions[i].transactionNumber);
cmd.Parameters.AddWithValue("#COMID", args[0]);
cmd.Parameters.AddWithValue("#curr", trans.payload.transactions[i].transactionCurrencyCode);
cmd.Parameters.AddWithValue("#amount", trans.payload.transactions[i].transactionAmount);
cmd.Parameters.AddWithValue("#dlDate", date);
cmd.Parameters.AddWithValue("#depositor", trans.payload.transactions[i].depositedBy);
cmd.Parameters.AddWithValue("#Details", trans.payload.transactions[i].paymentNotes);
cmd.Parameters.AddWithValue("#TransDate", DateTime.Parse(trans.payload.transactions[i].transactionValueDate));
cmd.ExecuteNonQuery();

OleDbDataReader does not read last record

I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
WriteToFile(query);
cmd2.CommandText = query;
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cn2;
using (oledbReader2 = cmd2.ExecuteReader())
{
while (oledbReader2.Read())
{
try
{
counter += 1;
query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
" , " + oledbReader2.GetValue(0).ToString() +
" , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
" , '" + oledbReader2.GetValue(1).ToString().Replace('\'', 'ยด') + "'" +
" , " + oledbReader2.GetValue(3).ToString() + ") ";
OleDbCommand cmd3 = new OleDbCommand(query, cn3);
WriteToFile(query);
cmd3.ExecuteNonQuery();
}
catch (Exception errorException)
{
actionSucceedded = false;
//eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
}
}
}
}

syntax error missing operator in date and time query expression

cmd.CommandText = "SELECT * FROM " + TableName + " WHERE"
+ " [TIME_STAMP]=#" + TimeStamp.ToString("dd-MM-yyyy HH:mm") + "#"
+ " AND [Slave_Id]='" + SlaveUnitID
+ " AND [Parameter]='" + Param
+ "' AND [Status]='" + Status
+ "' AND [Reading]='" + Reading + "'";
dr = cmd.ExecuteReader();
I am getting error in the above query.Tried but getting the same, Plz help it out
Try to use parameterized query
conn.Open();
string query = "SELECT * FROM " + TableName + " WHERE [TIME_STAMP] =#date "
+" AND [Slave_Id]=#sid AND [Parameter] =#param "
+" AND [Status] =#status AND [Reading] = #reading"
qlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("#date", TimeStamp);
cmd.Parameters.AddWithValue("#sid", SlaveUnitID);
cmd.Parameters.AddWithValue("#param", Param);
cmd.Parameters.AddWithValue("#status", Status);
cmd.Parameters.AddWithValue("#reading", Reading );
dr = cmd.ExecuteReader();

how to save imported excel in datagridview to database C#

how to save imported data from excel in datagridview to database in C#
I have saved records and exported to excel sheet, it exported along with data ID, now I have re-imported back to datagridview from excel. now I want to save data to database.
Important to know:
Database name "Records.sdf" using SQL Compact 3.5
DataGridViewName is RecordsDataGridView.
I'm using following code but it's not working.
public void SaveData()
{
// Save the data.
SqlCeConnection conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Records.sdf;Persist Security Info=False");
SqlCeCommand com;
string str;
conn.Open();
for (int index = 0; index < RecordsDataGridView.Rows.Count - 1; index++)
{
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '" + RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + ")";
com = new SqlCeCommand(str, conn);
com.ExecuteNonQuery();
}
conn.Close();
}
ERROR RECEIVING
Column Name not Valid, column name = Cash
Try this query string
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ",'"+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ",'" + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + "')";
You should pass varchar field enclosed with single quote.
var str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values("
+ RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '"
+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "',"
+ RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + ","
+ "'" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "'" + ","
+ RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + ","
+ "'" + dataGridView1.Rows[index].Cells[8].Value.ToString() + "'" + ")";
There are a few ways to do this.
Here is one method.
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
You can do this as well.
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
Something like this will work too.
private void buttonSave_Click_1(object sender, EventArgs e) // save to invoice
{
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "INSERT INTO invoice (p_code, p_name, p_category, p_price) " +
VALUES (#code, #name, #category, #price)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in MyTable.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#code", row["p_code"]);
sc.Parameters.AddWithValue("#name", row["p_name"]);
sc.Parameters.AddWithValue("#category", row["p_category"]);
sc.Parameters.AddWithValue("#price", row["p_price"]);
sc.ExecuteNonQuery();
}
con.Close();
}

Foreach Loop is not Working properly

There is problem in this code when I use parameterized query loop get one file name in string filename = Path.GetFileName(item); variable again and again
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + newtable));
int a = 0;
OleDbCommand cmd = new OleDbCommand();
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb";
cmd = mycon.CreateCommand();
mycon.Open();
DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = "00" + a.ToString();
// Response.Write("Number (" + a.ToString() + ") " + filename + " " + ips + " " + t1 + " " + v + " " + some + " " + some + "<br/><br/>");
// cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.AddWithValue("#p1", filename);
cmd.Parameters.AddWithValue("#p2", ips);
cmd.Parameters.AddWithValue("#p3", dateTime.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#p4", newtable);
cmd.Parameters.AddWithValue("#p5", TextBox4.Text);
cmd.Parameters.AddWithValue("#p6", TextBox3.Text);
cmd.ExecuteNonQuery();
}
But when I use normal insert query
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
loop is working alright and get all the name of files at specific location. Please let me know why ?Is there any problem in my logic ?
cmd.Parameters collection is not cleared between iterations. You should create parameters before the loop and set values in the loop, instead of using AddWithValue
cmd = mycon.CreateCommand();
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.Add('#p1',...);
...same for other params...
mycon.Open();
DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = "00" + a.ToString();
cmd.Parameters["#p1"].Value = filename;
...same for other params...
cmd.ExecuteNonQuery();
}
However you can just add cmd.Parameters.Clear() after cmd.ExecuteNonQuery() :)
As it noted in MSDN
OleDbParameterCollection.AddWithValue Method
Adds a value to the end of the OleDbParameterCollection
So engine doesn't see #p1 added on the second iteration because it already found #p1 added on the first one.

Categories

Resources