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.
Related
I need to include time in the database with this sql statement
the code works but the time is missing
string query = "UPDATE
Pri_loc_payment
SET
PAYMENT_STATUS_ID = " + status + $", SERVICE_STATUS = {ServiceStatus} PAYMENT_DATE = TO_DATE( '" + DateTime.Now.ToString("yyyy-MM-dd") + "', 'YYYY-MM-DD')
WHERE
ID in (" + concatIds + ")";
Although I do agree with the previous comments, if you had to make something work you could try this:
string query = $"UPDATE Pri_loc_payment SET PAYMENT_STATUS_ID = 1, SERVICE_STATUS = { "SomeServiceStatus"}, PAYMENT_DATE = TO_DATE({DateTime.Now:yyyy-MM-dd}) WHERE ID in ({"concatIds"})";
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 :)
I'm using SQL Server 2008, with a C# front end. I'm trying to pass a SQL string from C# to SQL Server, and there are 2 fields in my WHERE statement that sometimes might contain NULL values. I've got this code on my Page Load in the code-behind (this is for a report that will be placed in a datagrid):
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
string Val_Value = Convert.ToString(Request.QueryString["Val_Val"]);
string Trk_Value = Convert.ToString(Request.QueryString["Trk_Val"]);
string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
string sqlquery;
sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Unique_ID, CCM.CLAIM_ID as Claim_Number, ";
sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CCM.DATE_IMPORTED as Import_Date, CCM.Orig_Open_Date as Original_Review_Date, ";
sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, CCM.BENEFIT_TYPE1 as Benefit_Type1, ";
sqlquery = sqlquery + "CCM.BENEFIT_TYPE2 as Benefit_Type2, CCM.BENEFIT_TYPE3 as Benefit_Type3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
sqlquery = sqlquery + "WHERE CCM.Spare LIKE '" + DDL_Value + "' AND CCM.Cmplt LIKE '" + Val_Value + "' AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.DATE_IMPORTED >= '" + StDt_Value + "' AND CCM.DATE_IMPORTED <= '" + EnDt_Value + "'";
}
The code is sound, it works perfectly fine if a value is selected for all report parameters. The problem is CCM.Spare and CCM.Cmplt can have specific values chosen from a dropdown, or they can be left blank. If left blank, then they need to pull ALL values, whether they're NULL or not. When I leave one (or both) blank, that's where the SQL fails.
I tried checking for blanks and setting the variable equal to '%', but that obviously isn't working; it will only pick up records where there is a value in the field.
I want to do this with one statement if possible before I go cludging it with some If/Then/Else loops.
Is this possible?
try this, I just included the code for the first criteria.
As recommended above, don't concatenate your parameters; the second option is the best way to do it:
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE '" + DDL_Value + "'") + " AND ...";
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE #par1") + " AND ...";
Additionaly to increase the speed of your query you could do:
sqlquery = sqlquery +
"WHERE " + (DDL_Value != null ? "CCM.Spare LIKE #par1 AND " : "") + "...";
this will ignore the whole criteria on CCM.Spare if your parameter is null.
If you want all possible values of CCM.Spare and CCM.Cmplt, you simply need to leave off the predicate. Build a separate query (preferable using parametrized queries, as marc_s points out) that omits the WHERE clause referencing the empty dropdown value.
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.
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.