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();
Related
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);
}
}
}
}
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.
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();
Okay so I am trying to use parameters in C# sql code block but I am getting #Data in my SQL table please help
string connectionString = #"Network Library=DBMSSOCN;Data Source=**********,1433;database=*******;User id=*****;Password=******;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//
// Description of SQL command:
// 1. It selects all cells from rows matching the name.
// 2. It uses LIKE operator because Name is a Text field.
// 3. #Name must be added as a new SqlParameter.
//
using (SqlCommand command = new SqlCommand(
"INSERT INTO [dbo].[event_logs] ([event_level],[date_and_time],[source],[event_id],[task_category],[event_data],[channel],[computer_id],[created_at],[updated_at])VALUES('" + entry.EntryType + "','" + entry.TimeWritten + "','" + entry.Source + "','" + entry.InstanceId + "','" + entry.Category + "',' #Data ','" + logtype + "','" + computerID + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#Data", entry.Message));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
INSERTs don't return results. Use .ExecuteNonQuery() instead of .ExecuteReader().
You are getting #Data because you SQL string is formatted like "',' #Data ','" which is wrong, it is no more a variable, it is itself a SQL String.
What you need to do is fix the SQL query from "',' #Data ','" to "', #Data ,'" it will be fine then.
using (SqlCommand command = new SqlCommand(
"INSERT INTO [dbo].[event_logs] ([event_level],[date_and_time],[source],[event_id],[task_category],[event_data],[channel],[computer_id],[created_at],[updated_at])VALUES('" + entry.EntryType + "','" + entry.TimeWritten + "','" + entry.Source + "','" + entry.InstanceId + "','" + entry.Category + "', #Data ,'" + logtype + "','" + computerID + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')", connection))
{
// Add new SqlParameter to the command.
command.Parameters.Add(new SqlParameter("#Data", entry.Message));
command.ExecuteNonQuery();
}
You need to specify the name and data type in the constructor, and the value in the new object:
command.Parameters.Add("#Data", SqlDbType.VarChar).Value = entry.Message;
private void button2_Click(object sender, EventArgs e)
{
try
{
string sSQL = "INSERT INTO StuTable (Name, Batch,CGPA, DOB, Program,
Picture)VALUES (#Name, #Batch,#CGPA,#DOB,#Program,#Picture)";
SqlCommand objCmd = new SqlCommand(sSQL, conn);
objCmd.Parameters.Add("#Name", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Batch", SqlDbType.Int);
objCmd.Parameters.Add("#CGPA", SqlDbType.Float);
objCmd.Parameters.Add("#DOB", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Program", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Picture", SqlDbType.VarChar, 500);
//objCmd.Parameters["#RegdNo"].Value = Convert.ToInt32(textBox3.Text);
objCmd.Parameters["#Name"].Value = textBox4.Text;
objCmd.Parameters["#Batch"].Value = textBox5.Text;
objCmd.Parameters["#CGPA"].Value = textBox6.Text;
objCmd.Parameters["#DOB"].Value = maskedTextBox1.Text;
objCmd.Parameters["#Program"].Value = textBox8.Text;
objCmd.Parameters["#Picture"].Value = textBox9.Text;
objCmd.ExecuteNonQuery();
// MessageBox.Show("Record Added");
}
catch (Exception te)
{
MessageBox.Show(te.Message.ToString());
}
}
I am doing this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where JobID=" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
JobID is a uniqueidentifier
And I am getting this error:
Conversion failed when converting from a character string to uniqueidentifier.
What am I doing wrong?
The JobID field looks like this:
DB9424E5-1E73-4108-A855-B252E516A2A2
2EB17B8B-C0A1-46FE-82AF-37AEF2A8A6EC
C24F0460-7667-4A3A-8D8F-64B9728C2359
8DCDB020-8C7B-493E-9D21-719CBAFC16B6
This will be more secure (safe from SQL-injection), easer to read and understand, and faster because prepared statements get their execution plan cached. If you have different sql, it can't use a cached execution plan.
SqlCommand cmd =
new SqlCommand(
#"update FileLog set FaxStatus=#fs, FaxedPageCount=#ct, #dtFaxed=#dt, ......., where JobID=#id")
{CommandType = CommandType.Text};
cmd.Prepare();
cmd.Connection = connection;
cmd.Parameters["#id"].Value = row.ItemArray[0];
...
i found the solution. turns out you need to do this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"BiscomCode=" + "'" + row.ItemArray[5].ToString() + "', " +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
you have to convert it to a varchar first
It's very likely one of your job ids is not a valid Guid.
Here's a method to check for guid:
public static bool IsGuid(string input)
{
Regex isGuid = new Regex(#"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
try
{
return isGuid.IsMatch(input);
}
catch
{
return false;
}
}
So before issuing the query command do a check on the jobid. If it doesn't match, escape it and log it to revisit later.