I'm trying to update a database with OleDb and .Net4.5.
My updates are working good , even if i use simple quote on a filed, but, when i input a double quote on a field, oledb raise an exception because of this double quote.
Here is a an example of a request :
string strRequest = "update " + strNomTable.Trim() + " set "
+ "evenotes = " + '"' + m_strNote.ToString().Trim() + '"'
+ " where eveNum = " + '"' + strEvtNumeroString.Trim() + '"';
Have you an idea how i could avoid simple and double quotes ?
Note : I tried to use SQL Parametrized updates, bu my DataBase don't appear to support this.
Thanks a lot,
Best regards,
Nixeus
A few options come to mind. Since I do not know what kind of database you are using, I am just guessing:
Use parameters. I know you have tried it, but I would suggest to try again. If it failes, try the following:
Remove the comma for the "where" (one line up!).
Change all your double quotes inside your SQL-statement into single quotes. Literal text should be quotes like "'" + m_strNote.ToString().Trim() + "'" and not '"' + m_strNote.ToString().Trim() + '"'
Replace all single single quotes (') in your values with double single quotes (''): "'" + m_strNote.ToString().Trim().Replace("'", "''") + "'"
If you combine option 2 till 4 you will get this:
string strRequest = "update " + strNomTable.Trim() + " set "
+ "evenotes = '" + m_strNote.ToString().Trim().Replace("'", "''") + "' "
+ "where eveNum = '" + strEvtNumeroString.Trim().Replace("'", "''") + "'";
Visual Fox Pro Database and OleDbParameters
You can use OleDbParameters. Start the name with an #. So:
OleDbCommand command = new OleDbCommand(
"update " + strNomTable.Trim() + " set "
+ "evenotes = #evenotes "
+ "where eveNum = #eveNum");
command.Parameters.AddWithValue("#evenotes", m_strNote.ToString().Trim());
command.Parameters.AddWithValue("#eveNum", strEvtNumeroString.Trim());
Related
I'm confused at the moment about what it means exactly about my current syntax error issue while trying to save/insert answers into a table in my database. It worked fine when I attempted this with hardcoded variables but now is not the case.
Part of the error message:
Additional information: Incorrect syntax near ')'
Not sure what I'm doing wrong. Below is the code I'm using and the location where the error is pointing to. Thank you for any possible assistance and clarification.
protected void btnSaveAnswers_Click(object sender, EventArgs e)
{
Int32 int32StudentID = Convert.ToInt32(Session["StudentID"]);
Int32 int32QuestionID = Convert.ToInt32(Session["QuestionID"]);
String strAnswer = "";
// Save the student's answer to the Answer table.
// Develop the SQL call.
String strSQL = "";
strSQL = "INSERT ";
strSQL += "INTO Answer ";
strSQL += " (StudentID, QuestionID, Answer) ";
strSQL += "VALUES ";
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";
// Define the network connection to the SQL Server database.
SqlConnection objSqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["OPT"].ConnectionString);
// Create the SQL command object.
SqlCommand objSqlCommand = new SqlCommand();
objSqlCommand.Connection = objSqlConnection;
objSqlCommand.CommandType = CommandType.Text;
objSqlCommand.CommandText = strSQL;
// Open the connection.
objSqlConnection.Open();
// Execute the Insert statement.
objSqlCommand.ExecuteNonQuery();
// Close the connection.
objSqlConnection.Close();
this.Master.MessageForeColor = System.Drawing.Color.White;
this.Master.Message = "You have saved your answer for this question, click next to continue.";
}
First you should not be building SQL statements like this, it is prone to many problems, but your issue is with your string, you do not have single quotes around it:
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
Need to add the single quotes around strAnswer like I have above
Use parameters outlined here:
https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx
I agree with the comment about concatenation of strings. If you have to write a SQL query in code, you should user string interpolation.
If I had to do it, I would write it like this:
String strSQL = $"INSERT INTO Answer (StudentID, QuestionID, Answer) VALUES ( {int32StudentID}, {int32QuestionID}, '{strAnswer}')";
That said, that is not why you have a syntax error. You are missing single quotes around your string variable. Try this:
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
The error is at this line
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";
As per your SQL Query and database the field Answer is a field of type varchar or nvarchar. This type of field always takes value of string type. Which is done by you already. But SQL Server database accept these values inside the single quotation ''. Thus your solve is
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
as I've added a single quotation in front of strAnswer and at the last of strAnswer
Thank you.
It's my first SQL Parametrized update command in c# and i have a syntax error when i exectued my update.
Here is my code :
string maRequete = "UPDATE " + strNomTable + " set "
+ "evetype = #evetype ,"
+ "evedes = #evedes ,"
+ "evecli = #evecli ,"
+ "eveusermo = #eveusermo ,"
+ "eveinterv = #eveinterv where eveNum = " + '"' + strEvtNumeroString.ToString() + '"';
OleDbCommand DbCommand = new OleDbCommand(maRequete);
DbCommand.Parameters.Add("#evetype", OleDbType.VarChar);
DbCommand.Parameters.Add("#evedes", OleDbType.VarChar);
DbCommand.Parameters.Add("#evecli", OleDbType.VarChar);
DbCommand.Parameters.Add("#eveusermo", OleDbType.VarChar);
DbCommand.Parameters.Add("#eveinterv", OleDbType.VarChar);
DbCommand.Parameters["#evetype"].Value = m_strEvtType.ToString().Trim();
DbCommand.Parameters["#evedes"].Value = m_strDesignation.ToString().Trim();
DbCommand.Parameters["#evecli"].Value = m_strCodeClient.ToString().Trim();
DbCommand.Parameters["#eveusermo"].Value = m_strUserModification;
DbCommand.Parameters["#eveinterv"].Value = m_strCodeIntervenant.ToString().Trim();
try
{
string strStringConnect = #"Provider=vfpoledb.1;Data Source=" + m_strDirectoryDBF + "\\" + strDbfFile + ".dbf;Collating Sequence=general";
OleDbConnection DbConnection = new OleDbConnection(strStringConnect);
DbCommand.CommandType = System.Data.CommandType.Text;
DbConnection.Open();
DbCommand.Connection = DbConnection;
DbCommand.ExecuteNonQuery();
return "O";
}
catch (Exception Ex)
{
return Ex.Message;
}
Anyone have an idea where is my mistake ? In addition, i wrote in a old DBF file (Visual Foxpro) and i think i don't have access to log in order to debug the query :(.
Thanks a lot :)
Best regards,
Nixeus
Try using single quotes in your UPDATE statement instead of double quotes. The last line
+ "eveinterv = #eveinterv where eveNum = " + '"' + strEvtNumeroString.ToString() + '"';
should be
+ "eveinterv = #eveinterv where eveNum = '" + strEvtNumeroString.ToString() + "'";
change your command text as
string maRequete = "UPDATE " + strNomTable + " set "
+ "evetype = #evetype ,"
+ "evedes = #evedes ,"
+ "evecli = #evecli ,"
+ "eveusermo = #eveusermo ,"
+ "eveinterv = #eveinterv where eveNum = '" + strEvtNumeroString.ToString() + "'";
If you print out maRequete, and try executing it interactively, you will find the SQL syntax is incorrect. It seems likely you're using double-quotes to denote string constants; in SQL you should use single quotes for that. It's possible your data contains a single quote (i.e. an apostrophe). In that case, you need to add and extra one e.g.
INSERT ... values ('you''ll need two apostrophes for this');
These are just SQL rules. You have to give the server valid syntax if it's to execute your query.
Using the code I keep getting the error "Cannot get geometry object from data you send to the GEOMETRY field" However, if i copy and paste the string into an MySQL editor the query runs fine. Any thoughts?
string geoPOINTSTRING = splitZippy[4] + " " + splitZippy[5];
string atGvar = "GeomFromText('Point(" + geoPOINTSTRING + ")');";
string mySQLfinishedProcessing = " insert into zipcodes " +
"set zipcode = '" + zipcodeString + "'" +
",State = '" + StateString + "'" +
",City = '" + CityString + "'" +
",GEOPoint = #g"+
",StateCode = '" + StateCodeString2 + "'";
MySqlConnection configCON = new MySqlConnection(SQLStringClass.zipCONString);
MySqlCommand CounterLogs = new MySqlCommand(mySQLfinishedProcessing, configCON);
CounterLogs.Parameters.AddWithValue("#g",(string)atGvar);
configCON.Open();
CounterLogs.ExecuteNonQuery();
configCON.Close();
You are completely misusing parameters.
A parameter is a raw value.
You're setting GEOPoint to the literal string GeomFromText('Point(something)');
You need to put the actual values in parameters—zipcodeString, StateString, CityString, geoPOINTSTRING, and StateCodeString2.
You would then write GEOPoint = GeomFromText(#pointString), where pointString is a parameter holding "Point(" + geoPOINTSTRING + ")" (The string you want to pass to GeomFromText)
Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";
I've tried this:
select * from ourschema.mytable
where contains(mysearchablefield, #searchTerms) = 1;
Where #searchTerms was set to "search terms"
Unfortunately, it only produced an error:
ERROR [42610] [IBM][DB2/NT] SQL0418N A statement contains a use of a parameter marker that is not valid. SQLSTATE=42610
Is there a way to use parameterized queries for text search with DB2? If not, is there a document which describes the syntax in detail for manual (ugh) escaping of the search terms (quotes, etc)?
Instead of #field you need to use "?". Everything is basically the same.
Okay, here is a live code sample.
sqlStmt = "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 1 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE = 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE1 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE1 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE1 AND #TO_COMPLAINT_DATE1 " +
statusQry +
"UNION " +
"SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 2 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE <> 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE2 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE2 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE2 AND #TO_COMPLAINT_DATE2 " +
statusQry +
"ORDER BY DEPT_CODE, DIVISION_CODE, COMPLAINT_CODE, SORTORDER";
iDB2Command cmd = new iDB2Command(sqlStmt, conn);
conn.Open();
cmd.DeriveParameters();
conn.Close();
cmd.Parameters["#DEPT_CODE1"].Value = dept;
cmd.Parameters["#DIVISION_CODE1"].Value = serviceArea;
cmd.Parameters["#DEPT_CODE2"].Value = dept;
cmd.Parameters["#DIVISION_CODE2"].Value = serviceArea;
cmd.Parameters["#FROM_COMPLAINT_DATE1"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE1"].Value = Convert.ToDecimal(toDateString);
cmd.Parameters["#FROM_COMPLAINT_DATE2"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE2"].Value = Convert.ToDecimal(toDateString);
I hope this helps you out more.