UPDATE STATEMENT 2 tables c# - c#

my problem is that i tried all kind of solutions but it doesnt update my table here is my code behind of the button_click update:
protected void Button2_Click(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("Files/" + fileName));
SqlConnection cnx = new SqlConnection();
cnx.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["str"].ConnectionString;
SqlCommand cmd = new SqlCommand("Update Appel_offre set Titre_ao='" + TextBox4.Text + "',Description_ao='" + TextBox5.Text + "',Cout='" + TextBox6.Text + "',Type='" + DropDownList3.Text + "',Date='" + TextBox8.Text + "',Echeance='" + TextBox9.Text + "',Reference='" + TextBox7.Text + "',Piece_jointe='" + "Files/" + fileName + "',filename='" + fileName + "' where Id_ao = '" + Session["Id_ao"] + "' ", cnx);
SqlCommand cmd1 = new SqlCommand("Update Lot set Description=#desc,Reference=#ref,Type=#type where Titre = '" + Dropdownlst.SelectedItem.Value + "'",cnx);
cnx.Open();
cmd1.Parameters.AddWithValue("#desc", TextBox2.Text );
cmd1.Parameters.AddWithValue("#ref", TextBox3.Text );
cmd1.Parameters.AddWithValue("#type", DropDownList2.Text );
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
cnx.Close();
if (IsPostBack)
{
conff.Visible = true;
}
}

It's difficult to tell what's wrong here but I will gry to improve your code.
Maybe it also fixes the issue.
Use verbatim string literals, that makes your SQL query much better to read
Use the using statement to ensure that everything gets disposed properly
Don't use string concatenation to build your SQL query but SqlParameter, without exception. That prevents you from SQL injection and other issues.
Use not AddWithvalue but Add with the correct SqlDbType, otherwise the database makes guesses about the type of your parameter.
Pass the correct type and don't let the database cast your parameters, that also validates invalid input(f.e. incorrect date)
Code:
string updateApple = #"Update Appel_offre Set
Titre_ao = #Titre_ao,
Description_ao = #Description_ao,
Cout = #Cout,
Type = #Type,
Date = #Date,
Echeance = #Echeance,
Reference = #Reference,
Piece_jointe = #Piece_jointe,
filename = #filename
where Id_ao = #Id_ao;";
string updateLot = #"Update Lot Set
Description = #Description,
Reference = #Cout,
Type = #Type
where Titre = #Titre;";
using (var cnx = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["str"].ConnectionString))
using(var cmd_UpdateApple = new SqlCommand(updateApple, cnx))
using (var cmd_UpdateLot = new SqlCommand(updateLot, cnx))
{
cmd_UpdateApple.Parameters.Add("#Titre_ao", SqlDbType.VarChar).Value = TextBox4.Text;
cmd_UpdateApple.Parameters.Add("#Description_ao", SqlDbType.VarChar).Value = TextBox5.Text;
// ...
cmd_UpdateApple.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Parse(TextBox8.Text);
// ...
cnx.Open();
int updatedAppels = cmd_UpdateApple.ExecuteNonQuery();
cmd_UpdateLot.Parameters.Add("#Description", SqlDbType.VarChar).Value = TextBox2.Text.Text;
// ...
cmd_UpdateLot.Parameters.Add("#Titre", SqlDbType.VarChar).Value = Dropdownlst.SelectedItem.Value;
int updatedLot = cmd_UpdateApple.ExecuteNonQuery();
}
I've used DateTime.Parse, use DateTime.TryParse if the format can be invalid.

Related

syntax error missing operator in query expression c# using access as database

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.

my update c# code is not working,can i update two relational table at once?

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

ASP.NET is not sending a command to a SQL server

I have been assigned to create a website for a club at my school at kmhsmc.somee.com. I choose ASP for the language and I am having an issue with a sql function. If you go to the website above and click on join current liveclub session and fill in a bunch of junk in the textboxes at the top and hit join, it throws a SQL exception. here is the code:
UName = TextBox1.Text;
CompN = TextBox2.Text;
TMin = TextBox3.Text;
Name = TextBox4.Text;
TextBox1.Visible = false;
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox4.Visible = false;
string sql = "INSERT INTO table_name values (" + Name + "," + UName + "," + CompN + "," + TMin + "," + "NA" + "," + 0 + ")";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch
{
Response.Write("<script>alert('SQL error: try again later')</script>");
}
finally
{
conn.Close();
}
And for anyone who asks, I am 110% sure it is not the connection string because it works just fine on the calender page of the site.
Here is some other relevant information about this project:
I am doing it in C# and HTML ONLY (CSS and other designing things will be done by someone else later)
The server uses SQL server 2012
Problem : you are not enclosing the String types VARCHAR,NVARCHAR columns inside single quotes.
Solution : you need to enclose the String types inside single quotes.
Try This:
sqlCmd.CommandText = "INSERT INTO tablename(name) VALUES('yourname');
Suggestion : You should use Parameterised queries to avoid SQL injection attacks.
Complete Code: using parameterised sql queries
string sql = "INSERT INTO table_name values (#Name,#UName,#CompN,#TMin,#value1,#value2)";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Name",Name);
cmd.Parameters.AddWithValue("#UName",UName);
cmd.Parameters.AddWithValue("#CompN",CompN);
cmd.Parameters.AddWithValue("#TMin",TMin);
cmd.Parameters.AddWithValue("#value1","NA");
cmd.Parameters.AddWithValue("#value2",0);
cmd.ExecuteNonQuery();
}
your sql string is wrong.
UName = TextBox1.Text;
CompN = TextBox2.Text;
TMin = TextBox3.Text;
Name = TextBox4.Text;
TextBox1.Visible = false;
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox4.Visible = false;
string sql = "INSERT INTO table_name values ('" + Name + "','" + UName + "','" + CompN + "','" + TMin + "','NA', 0 )";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch
{
Response.Write( "<script>alert( 'SQL error: try again later' )</script>" );
}
finally
{
conn.Close();
}

How can i set a CommandText to my Search Button?

I'm trying to make a search button that when i enter an ID to a Textbox and press it , it goes to my private SQL server database and get the data row referred to that ID , But The exception handler brings me error because of my wrong CommandText .. Here is my Code
private void SearchBtn_Click(object sender, EventArgs e)
{
cn.ConnectionString = Properties.Settings.Default.ConStr;
if (ID.Text == "")
{
MessageBox.Show("Please Enter The ID you would like to search");
}
else
{
SqlCommand com = new SqlCommand();
cn.Open();
SqlParameter user = new SqlParameter("#ID", SqlDbType.Int);
SqlParameter FN = new SqlParameter("#First_Name",SqlDbType.NChar);
SqlParameter LN = new SqlParameter("#Last_Name", SqlDbType.VarChar);
SqlParameter Jb = new SqlParameter("#Job", SqlDbType.VarChar);
SqlParameter Ag = new SqlParameter("#Age", SqlDbType.VarChar);
SqlParameter ph = new SqlParameter("#Phone", SqlDbType.VarChar);
com.Parameters.Add(user);
com.Parameters.Add(FN);
com.Parameters.Add(LN);
com.Parameters.Add(Jb);
com.Parameters.Add(Ag);
com.Parameters.Add(ph);
com.Connection = cn;
Here is my Error :
*com.CommandText = "Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList) ";*
user.Direction = ParameterDirection.Input;
FN.Direction = ParameterDirection.Output;
LN.Direction = ParameterDirection.Output;
Jb.Direction = ParameterDirection.Output;
Ag.Direction = ParameterDirection.Output;
ph.Direction = ParameterDirection.Output;
FN.Size = 10;
LN.Size = 10;
Jb.Size = 10;
Ag.Size = 10;
ph.Size = 10;
user.Value = Convert.ToInt32(ID.Text);
try
{
com.ExecuteNonQuery();
FirstName.Text = FN.Value.ToString();
LastName.Text = LN.Value.ToString();
Job.Text = Jb.Value.ToString();
Age.Text = Ag.Value.ToString();
Phone.Text = ph.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I'm Using Visual Studio 2012 .
Thanks in Advance .
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
doesn't really look like SQL. Also I'm not quite sure why you're setting loads of parameters you're not using.
Maybe you meant something like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ID=#Id";
com.Parameters.AddWithValue("#Id", ID.Text);
Furthermore if that's your intention, then ExecuteNonQuery is wrong as that's for INSERT, UPDATE and other things that don't return a result.
Command text should be like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ....";
Remove most of your parameters, leave only input ones.
Instead of com.ExecuteNonQuery() use: SqlDataReader reader = command.ExecuteReader(); and using it read your data. Example article is here
Firstly:
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
Doesn't look like valid SQL to me.
I think you're looking to do something like this:
using (SqlConnection myConnection = new SqlConnection(connString))
{
string oString = " SELECT * from MyList WHERE (id = #id)";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.Add(new SqlParameter("#id", ID.Text));
myConnection.Open();
string name="";
string lastname ="";
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
name = oReader["name"].ToString(); // replace "name" with the name of the column you want
lastname = oReader["lastname"].ToString();
}
}
myConnection.Close();
return name + lastname;
You can use these values to set the text in your textboxes on your form:
YourNameTextbox.Text = name;
.. etc

UPDATE Query : Incorrect Syntax

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

Categories