I have a button in my windows forms which UPDATES every table. However, I am getting error SQLException was unhandled. Incorrect syntax near '='.
This is my code in Update Button:
public void btnUpdate_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
//MessageBox.Show(row.Cells[7].FormattedValue.ToString());
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("server=Test\\Test; Integrated Security=true; Database=Testing;");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "UPDATE dbo.JobStatus SET ShipTrackingNumber = '" + row.Cells[7].FormattedValue.ToString() + "' WHERE jobtableid = " + row.Cells[5].FormattedValue.ToString();
cmd.CommandText = "UPDATE dbo.JobStatus SET ShipMethodTransmitted = '" + row.Cells[8].FormattedValue.ToString() + "' WHERE jobtableid = " + row.Cells[5].FormattedValue.ToString();
cmd.CommandText = "UPDATE dbo.JobStatus SET DateShipTransmitProcessed = '" + row.Cells[9].FormattedValue.ToString() + "' WHERE jobtableid = " + row.Cells[5].FormattedValue.ToString();
cmd.CommandText = "UPDATE dbo.JobStatus SET ShipmentProcessedBy = '" + row.Cells[10].FormattedValue.ToString() + "' WHERE jobtableid = " + row.Cells[5].FormattedValue.ToString();
cmd.CommandText = "UPDATE dbo.JobStatus SET Critical = '" + row.Cells[11].FormattedValue.ToString() + "' WHERE jobtableid = " + row.Cells[5].FormattedValue.ToString();
cmd.CommandText = "UPDATE dbo.JobStatus SET ShipTransmitStatus = '" + row.Cells[13].FormattedValue.ToString() + "' WHERE jobtableid = " + row.Cells[5].FormattedValue.ToString();
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
catch (Exception e)
{
MessageBox.Show("Update Failed!!!");
}
}
}
Can anyone tell me what is wrong with these statements? Thanks!
Why not simply do it in a single update statement. So something like:
var sql = new StringBuilder();
sql.AppendLine( "UPDATE dbo.JobStatus" );
sql.AppendLine( "Set ShipTrackingNumber = #TrackingNumber" );
sql.AppendLine( ", DateShipTransmitProcessed = #DateShipTransmitProcessed" );
sql.AppendLine( ", ShipmentProcessedBy = #ShipmentProcessedBy" );
sql.AppendLine( ", Critical = #Critical" );
sql.AppendLine( ", ShipTransmitStatus = #ShipTransmitStatus" );
sql.AppendLine( "Where jobtableId = #jobTableId" );
cmd.Connection = sqlConnection1;
cmd.CommandText = sql.ToString();
cmd.Parameters.AddWithValue("#TrackingNumber", row.Cells[7].FormattedValue);
cmd.Parameters.AddWithValue("#DateShipTransmitProcessed", row.Cells[8].FormattedValue);
cmd.Parameters.AddWithValue("#ShipmentProcessedBy", row.Cells[9].FormattedValue);
cmd.Parameters.AddWithValue("#Critical", row.Cells[10].FormattedValue);
cmd.Parameters.AddWithValue("#ShipTransmitStatus", row.Cells[11].FormattedValue);
cmd.Parameters.AddWithValue("#jobTableId", row.Cells[5].FormattedValue);
Aside from what was mentioned in my comment; I don't see anything wrong with the syntax of your SQL. It's quite possible that your FormattedValue has an invalid character like a ' in the string itself, which would lead to a SQL error. Print out the value of the CommandText itself after the string has been built to see what it actually looks like.
Your UPDATE statement is incorrect. UPDATE syntax is:
UPDATE table
SET
column1 = 'value',
column2 = 'value2'
WHERE
condition;
You are overwriting your statement every time you assign to cmd. You probably want something more like:
cmd = "UPDATE table";
cmd += "SET column1 = '" + value + "',";
cmd += "SET column2 = " + intValue;
cmd += "WHERE idRow = '" + rowToUpdateValue + "'";
Also, if this doesn't help, check that you are not trying to check an INT column using a 'char' value.
Please check your conditions thus:
if(row.Cells[5].FormattedValue.ToString())
then execute update query
Related
I'm trying to update my data in C# Win Form.
I created a button "update", but whenever I run it, I don't see any changes in the table and any occurring errors
void insertdata() {
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM airport";
adapter.SelectCommand = cmd;
table.Clear();
adapter.Fill(table);
dgv.DataSource = table;
}
private void button_update_Click(object sender, EventArgs e)
{
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE airport SET p_name = '"+textBox2.Text+ "',p_age = '" + textBox3.Text + "', c_name = '" + textBox4.Text + "', date = '" + textBox5.Text + "', city_t = '" + textBox6.Text + "', city_f ='" + textBox7.Text + "', trip_num = '" + textBox8.Text + "', plane_type = '" + textBox9.Text+"' WHERE p_id = '"+textBox1+"'";
cmd.ExecuteNonQuery();
insertdata();
}
I've tried to add
connection.Open();
connection.Close();
However, I keep getting: "System.InvalidOperationException: "The connection was not closed. The connection is open."
Could there be any change in my code for updating the rows in the table, as whenever I run it I don't get any errors.
Please note the you wrote
WHERE p_id = '"+textBox1+"'
Instead of
WHERE p_id = '"+textBox1.Text+"'
Probably you don't have an ID that equals to the textBox...
I'm getting syntax error in all my inputs into the textboxes.
In my database all the requirement is string other than the ID which is an autonumber, I try to search for possible answer but all didn't work or maybe I just missed some answer
Here is the error:
Syntax error (missing operator) in query expression ''hasdasd'password
= 'h'account_Type='Manager'Name='h'Middle_Name='h'Surname'h'address'h'BirthDate='3/17/1999'Mobile_Number'65465''.
Code:
private void update_Click(object sender, EventArgs e)
{
DateTime bdate = DateTime.Parse(birthdate.Value.ToShortDateString());
DateTime currentDate = DateTime.Parse(DateTime.Now.Date.ToShortDateString());
int age = currentDate.Year - bdate.Year;
String id = emp_view.SelectedRows[0].Cells[0].Value + String.Empty;
int id1 = Int32.Parse(id);
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Employee_Details set username = '" + username.Text +
"'password = '" + password.Text +
"'account_Type='" + accountType.Text +
"'Name='" + name.Text +
"'Middle_Name='" + middlename.Text +
"'Surname'" + surname.Text +
"'address'" + address.Text +
"'BirthDate='" + birthdate.Value.ToShortDateString() +
"'Mobile_Number'" + mobilenumber.Text +
"'where ID = '" + id1 + "'";
if (username.Text.Equals("") ||
username.Text.Equals("") ||
password.Text.Equals("") ||
middlename.Text.Equals("") ||
surname.Text.Equals("") ||
address.Text.Equals("") ||
accountType.Text.Equals("") ||
mobilenumber.Text.Equals("")
)
{
MessageBox.Show("Please fill all fields.");
con.Close();
}
else if (age < 18)
{
MessageBox.Show("You are not allowed to work because you are under age..");
con.Close();
}
else
{
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(username.Text + "is now updated on database.");
list();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In your existing code, there are issues like.
1- Column in update are not separated by ","
2- All string are not separated using quotes ''
You should always avoid writing queries inline by concatenation of string. This will make you code vulnerable to SQL Injection.
To read more about SQL Injections check here
Change your code like following using command parameters.
cmd.CommandText = "update Employee_Details set [username] = #un, [password] = #pw, [account_Type]= #at, [Name] = #nm, [Middle_Name]= #mn, [Surname]= #sn, [address]= #add, [BirthDate] = #bd, [Mobile_Number] = #mn WHERE [Id]=#id";
cmd.Parameters.Add("#un", OleDbType.VarChar).Value = username.Text;
cmd.Parameters.Add("#pw", OleDbType.VarChar).Value = password.Text;
cmd.Parameters.Add("#at", OleDbType.VarChar).Value = accountType.Text;
cmd.Parameters.Add("#nm", OleDbType.VarChar).Value = name.Text;
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = middlename.Text;
cmd.Parameters.Add("#sn", OleDbType.VarChar).Value = surname.Text;
cmd.Parameters.Add("#add", OleDbType.VarChar).Value = address.Text;
cmd.Parameters.Add("#bd", OleDbType.Date).Value = Convert.ToDateTime(birthdate.Value);
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = mobilenumber.Text;
cmd.Parameters.Add("#id", OleDbType.VarChar).Value = id1;
Note: You need to correct the datatype based on your table structure as it is now known to me.
Your completely malformed SQL should look like:
cmd.CommandText = "update Employee_Details set " +
"username = '" + username.Text + "',"+
"[password] = '" + password.Text + "'," +
"account_Type = '" + accountType.Text + "'," +
"[Name] = '" + name.Text + "'," +
"Middle_Name = '" + middlename.Text + "'," +
"Surname = '" + surname.Text + "'," +
"address = '" + address.Text + "'," +
"BirthDate = #" + birthdate.Value.ToString("yyyy'/'MM'/dd") + "#," +
"Mobile_Number = '" + mobilenumber.Text + "' " +
"where ID = " + id1 + "";
That said, DO use parameters as already explained. Much easier and safer.
I am new to the C# programming. Facing the problem Incorrect syntax near 'First_Name'.! in the given below code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name ='" + fname.Text + "'");
//'" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("You Have Successfully Updated");
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}
Problem : You forgot to add word SET after your table name in update statement.
Solution1 : Add the word SET after table name in Update query (Don't Recommend this)
"update Customer_Info SET First_Name ='" + fname.Text + "'"
Warning : Your query is open to sql injection attacks.please use parameterised queries to avoid them
Solution 2: Using Parameterised Queries
Replace This:
SqlCommand cmd = new SqlCommand("update Customer_Info SET First_Name
='"+fname.Text+"'");
With This:
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name = #fname");
cmd.Parameters.AddWithValue("#fname" , fname.Text);
Your problem not in C#, in SQL syntax (you miss set keyword)
SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");
you are missing SET keyword:
update Customer_Info SET First_Name ='" + fname.Text + "'"
and also provide where clause otherwise it will update all the records in your table.
You are missing set keyword in query you have to place set like this
SqlCommand cmd = new SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");
i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here
I've tried this for several hours but I cannot figure it our what's wrong
var cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = mySqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"select Calle.Id_Calle FROM" +
"TominPredial.Calle as Calle,"+
"TominPredial.Colonia as Col," +
"TominPredial.Poblacion as Pob" +
"WHERE Calle.Nombre = #NombreCalle" +
"and Col.Id_Colonia = #id_col and Pob.Id_Poblacion = #id_pob";
cmd.Parameters.Add("#NombreCalle", nombreCalle);
cmd.Parameters.Add("#id_col", id_col);
cmd.Parameters.Add("#id_pob", id_pob);
cmd.ExecuteScalar()
It says incorrect syntax near "Calle"
There is no space between the lines:
"select Calle.Id_Calle FROM" +
"TominPredial.Calle as Calle,"+
"TominPredial.Colonia as Col," +
"TominPredial.Poblacion as Pob" +
"WHERE Calle.Nombre = #NombreCalle" +
"and Col.Id_Colonia = #id_col and Pob.Id_Poblacion = #id_pob";
This will make the query ... FROMTominpredial.calle ... pobWHERE .. which will generate a syntax error.
You have to put spaces between the keywords in the end of the lines. Something like so:
...
"select Calle.Id_Calle FROM" +
" TominPredial.Calle as Calle,"+
" TominPredial.Colonia as Col," +
" TominPredial.Poblacion as Pob" +
" WHERE Calle.Nombre = #NombreCalle" +
" and Col.Id_Colonia = #id_col and Pob.Id_Poblacion = #id_pob";
/\
put a Spaces here