Syntax Error on a Sql Parametrized update command - c# - c#

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.

Related

MySqlDataAdapter Update table that uses Inner Join

I'm tring to add the Insert, Update and Delete commands to a MySqlDataAdapter which has the data added to it with the command:
//iec211.4521studenti
string lv_sObsTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti'";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObsTable + " o INNER JOIN " + lv_sStudTable + " s USING (idStudent) ORDER BY s.nume ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
I've serched for an answer and I've found two possible solutions for UPDATE, but both of them give me an error:
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
//VERSION 1
string lv_sCommand = "UPDATE o SET s.idStudent=#idStudent, o.observatie=#observatie FROM " + lv_sObsTB + " AS o INNER JOIN " + lv_sStudTB + " s ON o.idStudent=s.idStudent ";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
//VERSION 2
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET " + "idStudent=#" + lv_sStudTB + ".idStudent, observatie=#observatie WHERE idObservatie=#idObservatie AND " + lv_sObsTB + ".idStudent IN (SELECT " + lv_sStudTB + ".idStudent FROM " + lv_sStudTB + ")";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#" + lv_sStudTB + ".idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
The error message for the first version is : "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 'FROM iec211.4521observatii ASS o INNER JOIN iec211.4521studenti s ON o.id' at line 1"
The error message for the second version is: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 '.4521studenti'.idStudenti, observatie='test' WHERE idObservatie=1 ANDiec211.' at line 1"
I don't know how to use the MySQL commands in combination with MySqlCommand and MySqlDataAdapter.
Until now I've used the following command to obtain data for my table:
string lv_sObservatiiCommand = "SELECT * FROM `" + mv_sDatabase + "`.`" + mv_sGroup + "observatii` ORDER BY idStudent ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
In combination with MySqlCommandBuilder to get the update command and the parameters that needed to be setted:
lv_sqlCommandBuilder = new MySqlCommandBuilder(mv_dtAdapterObservatii);
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommandBuilder.GetUpdateCommand();
Can someone please explain to me how to correctly add the insert, update and delete commands to a MySqlDataAdapter that contains an INNER JOIN between 2 tables ?
I know that each table must be in a different data adapter, and they are. The "4521studenti" table is inside "mv_dtAdapterStudenti", which is not included in the code above.
Thank you for the help and I hope this won't be considered as a bad post. :)
Okey. I think I've figured it out.
This is the SELECT command for 4521observatii:
string lv_sStudent = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sObservatii = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObservatii + " o INNER JOIN " + lv_sStudent + " s USING (idStudent) ORDER BY s.nume ASC";
// Read data from the server for the current table and add it to the DataSet
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
And this is the code for the UPDATE command, inside a different method:
// `iec211`.`4521observatii`
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
// `iec211`.`4521studenti`
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sSelectStudenti = "(SELECT idStudent FROM " + lv_sStudTB + " WHERE idStudent=#idStudent)";
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET idStudent="+ lv_sSelectStudenti + ", observatie=#observatie WHERE idObservatie=#idObservatie";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
mv_dtAdapterObservatii.UpdateCommand.Connection = mv_sqlConnection;
The idea is that when I use INNER JOIN I bring data from two different tables and put them together. When I used the UPDATE command, the program didn't know which table he was using and gived those errors.
So I thought what if I update the values of 4521observatii and for the column that is used as FOREIGN KEY I assign the value from 4521studenti.
I know it's like "Tell me your name so I can tell you your name.", but it worked for me.
I hope this will help others and you have a better and cleaner solution, pleas tell me :)

Issues with the update query SQL

am writing a c# code in which am trying to update 4 of the 10 columns of the table. Here is my function type in which am sending arguments for the query:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
Now what happens is that i call this function somewhere in my program providing values in argument:
checkout_visitor(chk_in,chk_out,t_out,dt_out,idcardnum);
The query am using to update my columns is given by:
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = "+ v_idd;
Given me exception incorrect syntax near chkout. Where am i wrong?? is the syntax correct? how do i correct it?
code:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
{
try
{
connection.Open();
String query = "select v_id from visitor where visitor.cnic=" + cnic;
command = connection.CreateCommand();
command.CommandText = query;
visitor_id = command.ExecuteScalar().ToString();
int v_idd = Int32.Parse(visitor_id);
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = " + v_idd;
//String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = " + time_out + ",[date_out] =" + date_out + " where visit_detail.v_id = " + v_idd;
command = connection.CreateCommand();
command.CommandText = query2;
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
catch (Exception e)
{
return -1;
}
}
Problem :
1.you are not seperating the Parameters properly using comma , .
2.you are not giving the sapace between SET and check_in parameter.
Try This:
String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = '" + time_out + "',[date_out] ='" + date_out + "' where visit_detail.v_id = "+ v_idd;
Do you see the resulting query? It seems to me you're missing some comma, but you should print (and post) the resulting query to have a better understanding of the issue.
You are missing ',' between the column names.
Its like Update Table Set col1=3,col2='test'
The problem is that query2 string will be something along the lines:
UPDATE visit_detail SET[check_in] = " 1[check_out] = 2[time_out] = some time[date_out] =some datewhere visit_detail.v_id = 5
So you can already see that there's datewhere that is incorect, there are also no ' characters around string parameters, and no commas between parameters.
Quick fix to that would be:
String query2 = String.Format("UPDATE visit_detail SET [check_in]={0}, [check_out]={1}, [time_out]='{2}', [date_out]='{3}' where visit_detail.v_id={4};", check_inn, checkout, time_out, date_out, v_idd);
But this is still not valid. If time_out contains ' characters, you'll again receive an error.
What you should really use is this:
SqlCommand.Parameters
This is a proper way of passing paramters to your command, all the problems will be taken care of for you.

Error while running update query for access database

This is my code:
OleDbConnection con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "/shoping mall.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("update RecordofItems set RecordofItems.Bill_no = " + textBox1.Text + ", RecordofItems.Received_from = '" + textBox62.Text + "', RecordofItems.Item_Code = " + textBox2.Text + ", RecordofItems.Quantity = " + textBox32.Text + ", RecordofItems.Sale_Rate = " + textBox47.Text + " where Item_Name = '" + textBox17.Text + "'", con);
int x = 0;
x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("record deleted" + x);
}
else
{
MessageBox.Show("no record exixt");
}
con.Close();
I want to update selected columns in my "RecordofItems" table that has 10 columns but I want to update only 6 selected columns, when I run the query it shows error "no value for one or more required paremeter" What to do ? please help me as soon as you can.
the error No value given for one or more required parameters usually comes when you have misplaced single quote.
try these two.
try assigning your numerical db columns a numerical value viz update your query with these:
RecordofItems.Bill_no = " + Convert.ToInt32(textBox1.Text) + ",
RecordofItems.Item_Code = " + Convert.ToInt32(textBox2.Text) + ",
RecordofItems.Quantity = " + Convert.ToInt32(textBox32.Text) + ",
RecordofItems.Sale_Rate = " + Convert.ToInt32(textBox47.Text) +
or use whatever suitable numerical converter applies to your columns.
one of your text fields might have a single quote in it, so try replacing/updating your text fields like this:
RecordofItems.Received_from = '" + textBox62.Text.Replace("'","''") + "',
so basically, replace single quote with two single quotes.
see if these solve your issue.
Also, do note, never create your sql query by concatenating textboxes(strings). use command parameters. they will save you from sql injection.

Why my query return null

I want to ask why query return null and not update what i want. Sorry I'm still new with asp.net and c#
myquery = "UPDATE kenderaan SET buatan = " + "'" + carmake + "'" + "," +
"model = " + "'" + carmodel + "'" + "," +
"no_enjin = " + "'" + carenjin + "'" + "," +
"cc = " + carcc + "," +
"seatCapacity = " + carseat + "," +
"tahunBuatan = " + caryear + " WHERE no_kenderaan = " + "'" + carid + "'" + "," +
"AND ic = " + "'" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
restructure your code into this, use Connection object, Command Object, using statement.
string myquery = "UPDATE kenderaan SET buatan = #carmake ," +
" model = #carmodel ," +
" no_enjin = #carenjin ," +
" cc = #carcc ," +
" seatCapacity = #carseat ," +
" tahunBuatan = #caryear " +
"WHERE no_kenderaan = #carid " +
" AND ic = #cusid ";
using (MySqlConnection _conn = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand _comm = new MySqlCommand())
{
_comm.Connection = _conn;
_comm.CommandText = myquery;
_comm.CommandType = CommandType.Text;
_comm.Parameters.AddWithValue("#carmake",carmake);
_comm.Parameters.AddWithValue("#carmodel",carmodel);
_comm.Parameters.AddWithValue("#carenjin",carenjin);
_comm.Parameters.AddWithValue("#carcc",carcc);
_comm.Parameters.AddWithValue("#carseat",carseat);
_comm.Parameters.AddWithValue("#caryear",caryear);
_comm.Parameters.AddWithValue("#carid",carid);
_comm.Parameters.AddWithValue("#cusid",cusid);
try
{
_conn.Open();
_comm.ExecuteNonQuery();
MessageBox.Show("Updated!");
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString()); // as mentioned on the comment
}
}
}
Reasons why you need to parameterized your query:
avoids SQL Injection
makes your code more readable
etc.. :D
Sources
AddWithValue
Add (recommended and leaving you this as an assignment :D)
Create a DbCommand to execute the Update statement by using ExecuteNonQuery() method. If you are using SQL Server then you can use this piece of code snippet:
using System.Data.SqlClient;
string query = "UPDATE kenderaan SET buatan = #carmake" +
", model = #carmodel" +
", no_enjin = #carenjin" +
", cc = #carcc" +
", seatCapacity = #carseat" +
", tahunBuatan = #caryear" +
" WHERE no_kenderaan = #carid AND ic = #cusid";
using (SqlConnection conn = new SqlConnection("<connection string>"))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#carmake", carmake);
cmd.Parameters.AddWithValue("#carmodel", carmodel);
cmd.Parameters.AddWithValue("#carenjin", carenjin);
cmd.Parameters.AddWithValue("#carcc", carcc);
cmd.Parameters.AddWithValue("#carseat", carseat);
cmd.Parameters.AddWithValue("#caryear", caryear);
cmd.Parameters.AddWithValue("#carid", carid);
cmd.Parameters.AddWithValue("#cusid", cusid);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try this code in place of your code:
and make sure that varchar parameters are compare to string values.
string myquery = "UPDATE kenderaan SET buatan = '" + carmake + "',model = '"+
carmodel + "',no_enjin = '" +carenjin + "',cc = " + carcc + ",seatCapacity = " +
carseat + ",tahunBuatan = " + caryear +
" WHERE no_kenderaan = '" + carid + "' AND ic = '" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
UPDATED: Apologize, I had just corrected your query with your where condition I just removed comma which you used to separate two condition.
To avoid SQL Injection Attacks, Use one of these :
1) Parameters with Stored Procedures
2) Use Parameters with Dynamic SQL
3) Constrain Input
you can find more information over HERE

How can you use parameterized statements with DB2 Text Search?

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.

Categories

Resources