c# mysql - update field value to include \r\n using mySqlParameter - c#

I'm trying to update a column in a row with a new value. the new value is in a variable, and the value contain a new line in it.
This method receive as dictionary the column name and values need to change, and create a dynamic update command.
The Code is working for any other row in the table, but when a newline is involved, and SQL Error saying: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
var valueStr = "";
for (var i = 0; i < srcRow.Count; i++)
{
valueStr += string.Format("{0} = ?prm{1}", srcRow.Keys.ElementAt(i),i);
if (i < srcRow.Count - 1)
valueStr += ", ";
var query = string.Format("UPDATE {0} SET {1} WHERE {2}", table, valueStr, pkey);
try
{
using (var cmd = destConn.CreateCommand())
{
cmd.CommandText = query;
for (int i = 0; i < srcRow.Count; i++)
{
cmd.Parameters.AddWithValue("?prm" + i.ToString(),srcRow.Values.ElementAt(i));
}
cmd.ExecuteNonQuery();
}
}
Thanks
Shimshon

Try replacing \r\n with \\r\\n,
MySQL receive it and it will escape to database.

Related

update multiple rows using list of id in c#

I'm having list of ids and I want to update the database table. I'm doing something like this:
sql = "update table set col = 'something' where id in (#Ids)"
using (var connection = new SqlConnection(_connection)){
connection.Query(sql, new { Ids = ids});
}
The error is:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
the simpleset way is this:
var parameters = new string[ids.Length];
var cmd = new SqlCommand();
for (int i = 0; i < ids.Length; i++)
{
parameters[i] = string.Format("#Id{0}", i);
cmd.Parameters.AddWithValue(parameters[i], ids[i]);
}
cmd.CommandText = string.Format("update table set col = 'something' where id in ({0})", string.Join(", ", parameters));
Solution : This is working for me
sql = "update table set col = 'something' where id in ("+string.Join(",", ids) + ");";
using (var connection = new SqlConnection(_connection)){
connection.Query(sql);
}

Must declare a scalar variable (C# and OleDb)

I know this question have been asked several times, but none of answers has helped me resolving this issue.
So, i'm writing data transfer utility, copying data from one table of OleDb database to table of another OleDb database.
I have read all the data from the source database, and i'm trying to write, but always gets this error
Must declare the scalar variable "#CategoryID"
Here's the code
// generating the insert string below
string insert = "INSERT INTO Categories VALUES (";
for(int i = 0; i < cols.Length; i++)
{
string coma = ", ";
if (i == cols.Length - 1)
coma = " )";
insert += "#" + cols[i] + coma;
}
try
{
while (src_reader.Read()) // reading from source database
{
dstcmd.CommandText = insert;
for (int i = 0; i < cols.Length; i++)
{
string temp = "#" + cols[i]; // cols is array of column names
dstcmd.Parameters.AddWithValue(temp, src_reader[cols[i]]);
// for debug purposes... below is screenshot of error
Console.Write(temp + " " + src_reader[cols[i]] + "\n");
}
Console.WriteLine("");
// point of error
dstcmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Here's the screenshot of error.
CategoryID is the first column of the table and hence the first value that is being inserted.
Any help will be appreciated. If i missed any information or something does not make sense, please do let me know.
Try changing this part:
// generating the insert string below
string insert = "INSERT INTO Categories VALUES (";
for(int i = 0; i < cols.Length; i++)
{
string coma = ", ";
if (i == cols.Length - 1)
coma = " )";
insert += "#" + cols[i] + coma;
}
to
// generating the insert string below
string insert = "INSERT INTO Categories VALUES (";
for(int i = 0; i < cols.Length; i++)
{
string coma = ", ";
if (i == cols.Length - 1)
coma = " )";
insert += "?" + coma;
}
You don't need to use parameter names in VALUES, but just ? placeholders. However, make sure the order of parameters when you add them matches the order of columns in the table.
Also, it may be better to explicitly specify the column list in the INSERT clause, like:
string insert = "INSERT INTO Categories (Col1, Col2, Col3, etc.) VALUES (";
See if you want to make that column names list dynamically generated too. But I suggest to get it working for the static column list first and then convert it to dynamic version.
Also, if you don't specify the column name list for INSERT you will have specify values for all columns.

Insert values from two gridviews into one sql column with Parameters.AddWithValue

NET web form page and I am attempting to pass values from two different gridviews into a single sql column. I am still new to parameterized querys so I am not to sure what the syntax would be for this. Any thoughts or suggestions are greatly apperciated.
My obvioulsy broken code is below
void AddIEKGNote()
{
for (int y = 0; y < EKGImpGV.Rows.Count; y++)
{
try
{
String qry = "sp_InsertPatientNoteCarotidDuplexImp";
com.Open();
SqlCommand con = new SqlCommand(qry, com);
con.CommandType = CommandType.StoredProcedure;
con.Parameters.AddWithValue("#Value", EKGImpGV.Rows[y].Cells[1].Text);
con.Parameters.AddWithValue("#Value", GridView3.Rows[y].Cells[1].Text);
con.Parameters.AddWithValue("#Order_T", Label22.Text.Trim());
con.Parameters.AddWithValue("#P_ID", Label6.Text.Trim());
j = con.ExecuteNonQuery();
if (j > 0)
{
Response.Write(" SUCCESS ");
}
else
{
Response.Write(" ERROR ! ");
}
}
finally
{
com.Close();
EKGReportReader();
SearchData();
BaseEKG();
PostEKG();
ImpressionReader1();
ImpressionReader2();
ImpressionReader3();
ImpressionReader4();
ImpressionReader5();
ImpressionReader6();
}
}
}
This will not work since I am trying to pass Value twice in this function and my stored procedure and my sql table only has one "Value" column.
I want to be able to do something like this:
con.Parameters.AddWithValue("#Value", EKGImpGV.Rows[y].Cells[1].Text , GridView3.Rows[y].Cells[1].Text);
replace this
con.Parameters.AddWithValue("#Value", EKGImpGV.Rows[y].Cells[1].Text);
con.Parameters.AddWithValue("#Value", GridView3.Rows[y].Cells[1].Text);
with this
string val = EKGImpGV.Rows[y].Cells[1].Text + GridView3.Rows[y].Cells[1].Text;
con.Parameters.AddWithValue("#Value", val);

Insert Into Statement doesn't throw an error but Data isn't inserted into table

I can't find the answer to this problem anywhere. I'm trying to insert data into a SQL Server table. Everything seems to be OK with the statement, no errors throw when the command executes, but data isn't updated into the table...
Here is my code:
public Boolean InsertRecordsToDB(string sColumns, String sParameters, string sValues, string sTable)
{
/// Split the parameter holding the values for the sql command parameters by the tab character and fill the appropriate arra\
String[] sMyCols;
sMyCols = sColumns.Split('\t');
List<String> lstCols = new List<String>();
for (int ii = 0; ii < sMyCols.Length; ii++)
{
lstCols.Add(sMyCols[ii]);
}
String[] sMyParams;
sMyParams = sParameters.Split('\t');
List<String> lstParams = new List<String>();
for (int ii = 0; ii < sMyParams.Length; ii++)
{
lstParams.Add(sMyParams[ii]);
}
/// Split the values param and fill the array. Using the parameter methodology as opposed to concatenating SQL strings prevents
/// SQL injection
string[] sMyValues;
sMyValues = sValues.Split('\t');
List<String> lstValues = new List<String>();
for (int ii = 0; ii < sMyValues.Length; ii++)
{
lstValues.Add(sMyValues[ii]);
}
/// Default connection string for the library project to be opened by the connection object
String sConnString = LibraryProject.Properties.Settings.Default.db_ConnectionString;
///First build the Sql string based on the criteria passed in
String sSql = "";
sSql = "Insert Into [" + sTable + "] (";
for (int j = 0; j < sMyCols.Length; j++)
{
int iParamLen = sMyCols.Length;
int iParamMinusOne = iParamLen - 1;
if (j.Equals(iParamMinusOne))
{
sSql += sMyCols[j] + ")";
}
else
{
sSql += sMyCols[j] + ",";
}
if (sSql.Substring(sSql.Length - 1).Equals(")"))
{
break;
}
}
sSql += " Values(";
for (int ii = 0; ii < sMyParams.Length; ii++)
{
int iParamLen = sMyParams.Length;
int iParamLenMinusOne = iParamLen - 1;
if (ii.Equals(iParamLenMinusOne))
{
sSql += sMyParams[ii].Substring(2) + ")";
}
else
{
sSql += sMyParams[ii].Substring(2) + ",";
}
if (sSql.Substring(sSql.Length - 1).Equals(")"))
{
break;
}
}
/// Create the connection object
using (SqlConnection oConn = new SqlConnection(sConnString))
{
oConn.Open();
{
try
{
/// With the connection open instantiate an Sql command object
SqlCommand oMyCmd = new SqlCommand(sSql, oConn);
oMyCmd.Connection = oConn;
oMyCmd.CommandType = CommandType.Text;
oMyCmd.CommandText = sSql;
int i = 0;
/// Assign the correct SQLDbType based on the preceding character of the parameter passed in (e.g. s_ = String/Text: b_ = Boolean: d_ = Date)
foreach (String sParam in sMyParams)
{
switch (sParam.Substring(0, 2))
{
case "s_":
oMyCmd.Parameters.Add(sParam.Substring(2), SqlDbType.Text);
break;
case "b_":
oMyCmd.Parameters.Add(sParam.Substring(2), SqlDbType.Bit);
break;
case "d_":
oMyCmd.Parameters.Add(sParam.Substring(2), SqlDbType.Date);
break;
default:
break;
}
oMyCmd.Parameters[sParam.Substring(2)].Value = lstValues[i];
i++;
}
oMyCmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
e.ToString();
}
return true;
}
}
}
Somebody please help me, I'm banging my head off of the wall here.
Here is the actual SQL statement after it's built:
Insert Into [tblBook] (ISBN, SERIAL_NUM, SUBJECT, TITLE, AUTHOR, PUBLISHER, GENRE)
Values(#ISBN, #SERIAL_NUM, #SUBJECT, #TITLE, #AUTHOR, #PUBLISHER, #GENRE)
The statement value was copied from the immediate window. I stopped execution at the oMyCmd.ExecuteNotQuery(); line.
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...

Passing Column name as string in mysql Insert query

this is what i am trying to do after receiving string from the serial port. i get whitespace between the data so i put two loops to eliminate them. i want to recieve data spanning multiple columns and a single row for every single run of do while loop.. Thanks in Advance
string text = sp.readline();
for (int i = 0; i < text.Length; )
{
p = text[i].ToString();
if (p != " ")
{
do
{
x += text[i].ToString();
s = text[i].ToString();
i++;
} while (s != " ");
try
{
string col = "column" + no.ToString();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO testdata("+col+")VALUES(?data)";
cmd.Parameters.Add("?data", MySqlDbType.VarChar).Value = x;
cmd.ExecuteNonQuery();
x = "";
p = "";
no++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} i++;
}
Sorry to say, you cannot, in any dialect of SQL, provide a table or column name as a bindable variable (or parameter). If it's working for MySQL that's terrific, but if you change over to any other DBMS make and model, it will suddenly stop working.
Also, INSERT means create a new row. You'll either need to insert all the column values at once in a single INSERT statement, or figure out how to INSERT one row and then UPDATE it for each new column value.
if you want to insert a single row having multiple column, then for loop is not required
following is for three columns
int no = 2;
cmd.CommandText = "INSERT INTO testdata(?col1,?col2,?col3)VALUES(?data1,?data2,?data3)";
cmd.Parameters.Add("?col1", MySqlDbType.String).Value = col1;
cmd.Parameters.Add("?col2", MySqlDbType.String).Value = col2;
cmd.Parameters.Add("?col3", MySqlDbType.String).Value = col3;
cmd.Parameters.Add("?data1", MySqlDbType.VarChar).Value = x1;
cmd.Parameters.Add("?data2", MySqlDbType.VarChar).Value = x2;
cmd.Parameters.Add("?data3", MySqlDbType.VarChar).Value = x3;
cmd.ExecuteNonQuery();

Categories