SQL Update statement error - c#

What's wrong with this SQL UPDATE statement?
try
{
int ageValue = Int32.Parse(age.Text);
string updateQuery = "Update \nMyTable \nSet \nFName = '" + fname.Text.ToString() + "',\nLName = '" + lname.Text.ToString() + "',\nAge = " + ageValue + ",\nCome = '" + from.Text.ToString() + "',\nTo = '" + to.Text.ToString() + "' Where Age=" + ageValue + ";";
MessageBox.Show(updateQuery);
OleDbConnection con = new OleDbConnection("provider=Microsoft.JET.OLEDB.4.0; Data Source = Database5.mdb");
OleDbCommand com = new OleDbCommand(updateQuery, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
I received that error
Syntax error in Update statement
What is wrong in that SQL Update?
Tools:
Microsoft Access 2003
Microsoft Visual Studio 2010 C#
Please help and thanks in advance

Try getting rid of the \n junk.
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() + "',LName = '" + lname.Text.ToString() + "',Age = " + ageValue + ",Come = '" + from.Text.ToString() + "',To = '" + to.Text.ToString() + "' Where Age=" + ageValue;
Output the result of the concatination and try to run it. If that doesn't work, post the result of the concatination here and someone should be able to help. Without knowing the result of the concatination, it's difficult to know what's wrong.

Try changing the query like this (removing \ns and the final ;)
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() +
"', LName = '" + lname.Text.ToString() + "', Age = " + ageValue +
", Come = '" + from.Text.ToString() + "', To = '" + to.Text.ToString() +
"' Where Age=" + ageValue;

I would suggest you put the Sql Profiler on and trace your update query because it is easy to read the concatenated query string

Hello you can try with this code
StringBuilder stringBuilder = new StringBuilder() ;
stringBuilder.Append("Update MyTable Set FName = ") ;
stringBuilder.Append(fname.Text.ToString()) ;
stringBuilder.Append(",\nLName = ") ;
stringBuilder.Append(lname.Text.ToString()) ;
stringBuilder.Append(",\nAge = ") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(",\nCome = ") ;
stringBuilder.Append(from.Text.ToString()) ;
stringBuilder.Append(",\nTo = ") ;
stringBuilder.Append(to.Text.ToString()) ;
stringBuilder.Append(" Where Age=") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(";") ;
var result = stringBuilder.ToString();

This is how I write my inline SQL in C sharp:
string strSQL = "";
strSQL += " Update MyTable Set ";
strSQL += " FName = '" + fname.Text.ToString() + "' ";
strSQL += " ,LName = '" + lname.Text.ToString() + "' ";
strSQL += " ,Age = '" + ageValue + "' ";
strSQL += " ,Come = '" + from.Text.ToString() + "' ";
strSQL += " ,To = '" + to.Text.ToString() + "' ";
strSQL += " Where Age = '" + ageValue + "' ";
Easy to read and works fine.
You can also add this just below your query before you connent to your database:
Response.Write(strSQL);
return;
this will show you whats being posted to the server and makes it a little easier to find errors.

Related

SQL statement in MS Access with parameters of type date

I have a SQL statement for querying in MS Access. I want to get the result of the transaction between dates.
This is my code:
DateTime pFromNew = Convert.ToDateTime(this.dateTimePicker1.Value.ToString("yyyy-MM-dd"));
DateTime pToNew = Convert.ToDateTime(this.dateTimePicker2.Value.ToString("yyyy-MM-dd"));
string pFrom = "#" + pFromNew.ToString() + "#";
string pTo = "#" + pToNew.ToString() + "#";
chrTrans.Series["Class"].Points.Clear();
oconn.Open();
OleDbCommand cmd = oconn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
//+ "' and valuedate between '"+ this.dateTimePicker1.Text +"' and '"+ this.dateTimePicker2.Text +"'";
cmd.ExecuteNonQuery();
What is wrong with this statement?
I always get this error:
DATA Type mismatch in criteria expression.
Remove the single quotes you have in your string... I will show you...
This line:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
Should be:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo;
The reason is that you already concatenated a # symbol around your date strings--and the single quote thus is not needed.
You are making this too complicated, converting back and forth three times.
It can be reduced to:
string pFrom = "#" + this.dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "#";
string pTo = "#" + this.dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd") + "#";
// snip
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo + "";

i am getting this error saving the data in Sql Server "conversion failed when converting date and/or time from character string.". below is my code:

string TJOBCODE1 = ddlJobCode.SelectedItem.Value;
string abc = ddlJobCode.SelectedItem.ToString();
string TJob_Name = abc.Substring(0, abc.IndexOf('['));
string TRo_Name = abc.Substring(abc.LastIndexOf('[') + 1);
TRo_Name = TRo_Name.Replace("]", "");
string TJOBCODE = TJOBCODE1;
SqlCommand fsql = new SqlCommand("SELECT COUNT(*) AS REC FROM [MTS_TV_RO_TC_FINAL] where JOB_CODE='" + TJOBCODE + "' AND AGENCY_CODE in( select agency_code FROM " + tmptvrlbktbl + ")", Global.con1);
SqlDataAdapter Fda1 = new SqlDataAdapter(fsql);
DataTable Fdt1 = new DataTable();
Fda1.Fill(Fdt1);
int DD = Convert.ToInt32(Fdt1.Rows[0].ItemArray.GetValue(0).ToString());
if (DD == 0)
{
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],'" + COMP_FROM + "','" + COMP_TO + "',GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
SqlCommand cmd1 = new SqlCommand(INSQURY, Global.con1);
cmd1.ExecuteNonQuery();
Alert.show1("Data Saved Successfully", this);
}
else
{
Alert.show1("Data Already Saved", this);
return;
}
The code was perfectly fine, there was an issue with the excel sheet. i changed the query to parametrized and changed the excel sheet as well and it worked.
Change insQury to
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],COMP_FROM, COMP_TO,GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
If COMP_FROM and COMP_TO are dates already you don't need to surround them with single quotation marks.

Syntax Error in UPDATE statement VS 2015

I get the Syntax Error in UPDATE statement whenever I try to update information in my Access database. I have tried moving things around and adding commas or taking away commas. I am stuck, any suggestions as to what I could do? The error is attached to the second cmd.ExecuteNonQuery(); at the bottom.
if (txtdateId.Text != "")
{
if (txtdateId.IsEnabled == true)
{
cmd.CommandText =
"insert into tbEmp(DateofService, AssociateName, DeviceType, DeviceModel, Serial, Issue, Part1, Part2, Part3, RepairedBy, Campus) Values('" +
txtdateId.Text + "','" + txtEmpName.Text + "','" + txtContact.Text + "','" + txttype.Text +
"','" + txtserial.Text + "','" + txtAddress.Text + "','" + txtpart1.Text + "','" + txtpart2.Text +
"','" + txtpart3.Text + "','" + txtrepaired.Text + "','" + txtcampus.Text + "')";
cmd.ExecuteNonQuery();
BindGrid();
MessageBox.Show("Device Added Successfully");
ClearAll();
}
else
{
cmd.CommandText = "update tbEmp set DateofService = ,'" + txtdateId.Text + ",AssociateName = '" + txtEmpName.Text + ",DeviceType = '" + txtContact.Text + ",DeviceModel = '" + txttype.Text + ",Serial = '" + txtserial.Text + ",Issue = '" + txtAddress.Text + ",Part1 = '" + txtpart1.Text + ",Part2 = '" + txtpart2.Text + ",Part3 = '" + txtpart3.Text + ",RepairedBy = '" + txtrepaired.Text + "where Campus = '" + txtcampus.Text;
cmd.ExecuteNonQuery();
BindGrid();
MessageBox.Show("Device updated");
ClearAll();
}
}
You missed several ' in you statement also you have one extra ' after DateofService. Your statement should be like this:
cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "',AssociateName = '" + txtEmpName.Text + "' , ...
Also I strongly recommend you to use parameterized queries to avoid SQL Injection like this:
In SQL:
cmd.CommandText = "update tbEmp set DateofService = #txtdateId ,...";
cmd.Parameters.AddWithValue("txtdateId",txtdateId.Text);
And for Access and OleDB:
cmd.CommandText = "update tbEmp set DateofService = ? , ....";
cmd.Parameters.AddWithValue("DateofService ",txtdateId.Text);
Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?
This is solution of your problem, but I'll prefer you do some add validation for SQL injection. First take the textbox value validate it then pass it query.
cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "' ,AssociateName = '" + txtEmpName.Text + "' ,DeviceType = '" + txtContact.Text + "',DeviceModel = '" + txttype.Text + "',Serial = '" + txtserial.Text + "',Issue = '" + txtAddress.Text + "',Part1 = '" + txtpart1.Text + "',Part2 = '" + txtpart2.Text + "' ,Part3 = '" + txtpart3.Text + "' ,RepairedBy = '" + txtrepaired.Text + "' where Campus = '" + txtcampus.Text + "'";

C# Update MS Acess data from code, my method doesn't work

Hi first here is my code:
OleDbConnection conexao = new OleDbConnection();
try
{
OleDbCommand comando = new OleDbCommand();
comando.Connection = conexao;
string query2 = "update Utilizador set Nome='" + nomeTextBox.Text + "' , DiaNascimento='" + diaNascimentoComboBox.Text + "' ,MesNascimento='" + mesNascimentoComboBox.Text + "' ,AnoNascimento='" + anoNascimentoComboBox.Text + "' , Altura='" + alturaTextBox.Text + "' , Sexo='" + sexoComboBox.Text + "' , Peso='" + pesoTextBox.Text + "' , CodGenetica='" + codGeneticaTextBox1.Text + "', Login='" + loginTextBox.Text + "' , Password='" + passwordTextBox.Text + "' where CodUtilizador= " + codutilizaor.Text + "";
string id = codutilizaor.Text;
string command = "update Utilizador set Nome= '" + nomeTextBox.Text + "' , Login= " + loginTextBox.Text + " where CodUtilizador= '" + id + "' ";
conexao.Open();
conexao.Close();
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ya" + ex);
}
I want to update all the fields but it doesn´t work, i saw many solutions here and in youtube but none solved my problem, and I tried very hard from myself to do it but it still doesn ´t work , please may you help mesolving this problem?
you missing a quote on query2:
...where CodUtilizador= '" + codutilizaor.Text + "";
you also have to execute the query with ExecuteNonQuery(); :
...
comando.Text=command;
comando.ExecuteNonQuery();
Last but not least consider using parameters, because you are exposed to SQL injection.
e.g:
string command = "update Utilizador set Nome= #None , Login=#Login where CodUtilizador=#ID";
comando.Parameters.AddWithValue("#Nome", nomeTextBox.Text);
comando.Parameters.AddWithValue("#Login", loginTextBox.Text);
comando.Parameters.AddWithValue("#ID", id);
Looks like you forgot to add the query to the command. You also forgot to actually execute it.
OleDbConnection conexao = new OleDbConnection("Add your connection string here");
try
{
string query = "update Utilizador set Nome='" + nomeTextBox.Text + "' , DiaNascimento='" + diaNascimentoComboBox.Text + "' ,MesNascimento='" + mesNascimentoComboBox.Text + "' ,AnoNascimento='" + anoNascimentoComboBox.Text + "' , Altura='" + alturaTextBox.Text + "' , Sexo='" + sexoComboBox.Text + "' , Peso='" + pesoTextBox.Text + "' , CodGenetica='" + codGeneticaTextBox1.Text + "', Login='" + loginTextBox.Text + "' , Password='" + passwordTextBox.Text + "' where CodUtilizador='" + codutilizaor.Text + "'";
conexao.Open();
var commandOne = new OleDbCommand(query, conexao);
commandOne.ExecuteNonQuery()
conexao.Close();
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ya" + ex);
}

Possible solution for locking the table in sqlserver using asp.net

I have been working on a software which uses database which is shared with multiple PCs. The project is all about to store missing baggage information. We have given a facility to copy the newly inserted record into the master DB.
Now what here happens is when multiple users are trying to update the db at the same time single item get stored for multiple time in the global DB.
So I have tried to use TableLock using serializable but I got nothing here.
Edit
query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN TRANSACTION;";
insertdata(query); //using cmd.ExecuteNonQuery();
query = "select * from Goods WITH (TABLOCKX)" ;
DataSet dsGoods = getdata(query, "config");//Function to get the data
updateitem();
query = "COMMIT TRANSACTION";
insertdata(query);//using cmd.ExecuteNonQuery();
And the updateitem() is as follow
public static void updateitem()
{
string query = "select * from config where param='lastsync'";
DataSet ds = dataaccess.getdata(query, "config");
query = "select isonlive,associateid,itemid,founddate,regdate,status,foundbyname,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,showonline,officeid,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item ";
String updatedDate =ds.Tables[0].Rows[0]["value"].ToString();
if (updatedDate != "")
{
query = "select isonlive,associateid,itemid,founddate,regdate,foundbyname,status,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,officeid,showonline,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item where updateat >= #updateat";
}
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(query);
if (updatedDate != "")
{
cmd.Parameters.AddWithValue("#updateat",DateTime.ParseExact(updatedDate,"dd-MM-yyyy HH:mm:ss",null,System.Globalization.DateTimeStyles.None));
}
DataRow dr;
ds = dataaccess.getdata(cmd, "item");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
int status = 0;
dr = ds.Tables[0].Rows[i];
if (dr["status"].ToString() == "Transferred")
{
status = 2;
}
else if (dr["status"].ToString() != "Received")
{
status = 1;
}
DateTime regdate = Convert.ToDateTime(dr["regdate"]);
DateTime founddate = Convert.ToDateTime(dr["founddate"]);
//returndatetime = String.Format("MMM dd yyyy H:mm:ss", returndate);
if (dr["showonline"].ToString() == "False")
{
status = 1;
}
if (dr["isdeleted"].ToString() == "true")
{
insertdata("delete from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'");
continue;
}
if (dr["isonlive"].ToString() == "true")
{
query = "update goods set Status='" + status + "',officeid='" + dr["officeID"] + "', notes='" + dr["notes"].ToString().Replace("'", "''") + "',ReturnedTo='" + dr["returnedtoname"].ToString().Replace("'", "''") + "',founddate=#founddate,ReturnedDate=#returndate,ReturnedBy='" + dr["returnedby"].ToString().Replace("'", "''") +
"',Model='" + dr["model"].ToString().Replace("'", "''") + "',ColorID='" + dr["color"].ToString().Replace("'", "''") + "',FoundWhere='" + dr["foundwhere"].ToString().Replace("'", "''") + "',MainCat='" + dr["categoryid"] + "',SubCat='" + dr["subcatid"] + "',ItemID='" + dr["item"] + "' where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'";
}
else
{
query = "select * from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "' and MainCat='" + dr["categoryid"] + "' and SubCat='" + dr["subcatid"] + "' and ItemID='" + dr["item"] + "'";
DataSet dsItems = getdata(query, "config");
if(dsItems.Tables[0].Rows.Count==0)
{
query = "insert into goods (AssociateID,ID,DateReg,Status,MainCat,SubCat,ItemID,Model,ColorID,FoundWhere,RegBy,FoundBy,ReturnedTo,ReturnedDate,ReturnedBy,Notes,IP,founddate,officeid) values('" + dr["associateid"] + "','" + dr["itemid"] + "',#regdate,'" + status + "'," +
"'" + dr["categoryid"] + "','" + dr["subcatid"] + "','" + dr["item"] + "','" + dr["model"].ToString().Replace("'", "''") + "','" + dr["color"].ToString().Replace("'", "''") + "'," +
"'" + dr["foundwhere"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["returnedtoname"].ToString().Replace("'", "''") + "',#returndate," +
"'" + dr["returnedby"].ToString().Replace("'", "''") + "','" + dr["notes"].ToString().Replace("'", "''") + "','',#founddate,'" + dr["officeID"].ToString() + "')";
}
}
SqlCommand sce = new SqlCommand(query);
if (dr["returneddate"].ToString() != "")
{
sce.Parameters.AddWithValue("#returndate", Convert.ToDateTime(dr["returneddate"]));
}
else
{
sce.Parameters.Add("#returndate", SqlDbType.DateTime).Value = DBNull.Value;
}
sce.Parameters.AddWithValue("#regdate", regdate);
sce.Parameters.AddWithValue("#founddate", founddate);
insertdata(sce);
query = "update item set isonlive = 'true',updateat=#updateDate where itemid = '" + dr["itemid"] + "'";
sce = new SqlCommand(query);
sce.Parameters.AddWithValue("#updateDate", DateTime.Now);
dataaccess.insertdata(sce);
}
catch (Exception ex)
{
App.writelog(ex.Message + "\n" + ex.StackTrace);
}
}
}
P.S.: I want it to be done though ASP.Net.

Categories