SQL query for update statement in (C#) - c#

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 + "'");

Related

incorrect syntax when I select, the error near the first name

I have a little problem with an error. but I have this command in another form and do not give me the error.
This is the code:
string select = "select CONCAT(nume,' ',prenume) from echipa where email=#EMAIL";
cmd.Connection = con;
if (bunifuCheckbox1.Checked == true)
{
con.Open();
cmd.CommandText = "Insert into clienti_fizici(nume,prenume,email,telefon,adresa,data_nasterii,data_ora,CNP,sex,judetprovenienta,temperamentclient,provenientaclient,descriere,numeagent)values('"
+ bunifuMaterialTextbox1.Text + "','" + bunifuMaterialTextbox2.Text + "','" + bunifuMaterialTextbox4.Text + "','" + bunifuMaterialTextbox8.Text + "','" + bunifuMaterialTextbox3.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss") + "','" + bunifuDatepicker1.Value.Date + "','" + bunifuMaterialTextbox11.Text + "','" + gender + "','" + bunifuMaterialTextbox12.Text + "','" + bunifuDropdown1.selectedValue + "','" + bunifuDropdown2.selectedValue
+ "','" + richTextBox1.Text + "','" + select + "')";
cmd.Parameters.AddWithValue("#EMAIL", loginform.Email);
MessageBox.Show("Datele au fost introduse in baza de date !");
cmd.ExecuteNonQuery();
con.Close();
}
and the error would be from that select.
First, you must never concatenate strings with user input to create SQL Statement. Instead, always parameterize your SQL statements. Otherwise you are risking SQL injection attacks.
Second, you can't use select inside the values clause.
What you can do add parameters or hard coded values to your select statement.
Third, SqlConnection and SqlCommand both implement the IDisposable interface and should be used as a local variable inside a using block.
A better code would look like this:
if (bunifuCheckbox1.Checked == true)
{
string sql = "Insert into clienti_fizici(nume, prenume, email, telefon, adresa, data_nasterii, data_ora, CNP, sex, judetprovenienta, temperamentclient, provenientaclient, descriere, numeagent) " +
"SELECT #nume, #prenume, #email, #telefon, #adresa, #data_nasterii, #data_ora, #CNP, #sex, #judetprovenienta, #temperamentclient, #provenientaclient, #descriere, CONCAT(nume,' ',prenume) " +
"FROM echipa where email = #EMAIL";
// Note: SqlConnection should be opened for the shortest time possible - the using statement close and dispose it when done.
using(var con = new SqlConnection(connectionString))
{
// SqlCommand is also an IDisposable and should be disposed when done.
using(var cmd = new SqlCommand(sql, con)
{
cmd.Parameters.Add("#nume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox1.Text;
cmd.Parameters.Add("#prenume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox2.Text;
//... Add the rest of the parameters here...
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar).Value = loginform.Email;
// Why is this here? MessageBox.Show("Datele au fost introduse in baza de date !");
con.Open();
cmd.ExecuteNonQuery();
}
}
}

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

Code for checking the same data present in table column

I am facing a problem, that in my customer info table the customer id, contact no & E-mail address should not be same for two or more customers.I also have set custmomerid as the primary key. Plz let me know how to get the warning message box for that, there is the same data already present while adding to database......
private void button1_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("insert into Customer_Info values('" + Custid.Text.ToString() + "','" + 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 Inserted");
this.customer_InfoTableAdapter1.Fill(this.cD_GalleryDataSet7Cust_add.Customer_Info);
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}
If i understood correctly, you need to prevent duplicate entries on customerID, contactNo and Email. The most straight forward answer is put the primary key on all three columns. This would throw a DuplicateRecord Exception when adding a record that already exists and you should properly catch it.
Another way is to check in the query (with execute scalar):
"IF EXISTS(select 1 from customer_info where customerID = ... and
contactNo = ... and email = ...)
BEGIN select -1 RETURN END
insert into Customer_Info values('.......... (your query)"
Hope that helps

Use right syntax error in Mysql

Am not able to fix the error below:
`"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 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.

How to execute 2 Sql statements with one button click

I've managed to run this query using wamp.
INSERT INTO guest (guestno,familyname)
VALUES(NULL,'Damn');
INSERT INTO reservation (reservationno, guestno)
VALUES(NUll,LAST_INSERT_ID())
However If I separately execute these 2 insert statements I will have a foreign key constraint.
I think the both of them need to be executed at the same time.
My questions are:
How to incorporate this into my c# winform code?
Is it possible to have 2 insert statements on one button?
When the user presses "add reservation" I would like the two MySQl query's to be executed.
Here's my insert statement:
private void button7_Click(object sender, EventArgs e)
{
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "<insert statement>";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
reader.Read();
}
UPDATED VERSION (DOESN'T WORK)
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
Form3 f3 = new Form3();
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "insert into guest (guestno, familyname) values (null, '" + textBox6.Text + "'); insert into reservation (reservationno, guestno) values (null, LAST_INSERT_ID())";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
reader.Read();
MessageBox.Show("Added Guest Reservation Successfully");
f3.guestList();
f3.reservationList();
Updated No.3 (STILL DOESN'T WORK)
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
dbcmd = new MySqlCommand("CreateGuestAndReservation", dbcon);
dbcmd.CommandType = CommandType.StoredProcedure;
dbcmd.Parameters.AddWithValue("familyName", "foo");
dbcmd.ExecuteNonQuery();
enter code here
You can't execute more than one statement on a given MySqlCommand.
Your best bet all around (maintainability, performance, readability) is to:
create a MySQL stored procedure for your 2 SQL statements.
call your stored proc using ExecuteNonQuery().
DELIMITER //
CREATE PROCEDURE CreateGuestAndReservation
(
IN familyName VARCHAR(255)
)
BEGIN
insert into guest (guestno, familyname)
values (null, familyName);
insert into reservation (reservationno, guestno)
values (null, LAST_INSERT_ID());
END//
DELIMITER ;
Call it from your WinForms code like this:
dbcon.Open();
cmd = new MySqlCommand("CreateGuestAndReservation", dbcon);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("?familyName", "foo");
cmd.Parameters.Add("?familyName", MySqlDbType.VarChar,255).Value = "foo";
cmd.ExecuteNonQuery();
The code below should work but I suspect you may have already tried it given that you are asking for help?
string sql = "INSERT INTO guest (guestno,familyname) VALUES(NULL,'Damn'); INSERT INTO reservation (reservationno, guestno) VALUES(NUll,LAST_INSERT_ID())";
If you need parameters, try this:
string sql = "INSERT INTO guest (guestno,familyname) VALUES(NULL,?familyName); INSERT INTO reservation (reservationno, guestno) VALUES(NUll,LAST_INSERT_ID())";
...
dbcmd.Parameters.Add("#familyName", MySqlDbType.VarChar, 80).Value = _familyName;
EDIT: You may need to run 2 insert commands. See here.
I would suggest having a way to get ids other than relying on automatic id generation like autoincrements of mysql and sql server, which are very limiting. If you use a HILO id generator you first obtain id, and then execute a couple of inserts in a single transaction no problem, since you know your parent id beforehand.
It will not solve your immediate problem, but it will help tremendeously in future with your application, especially if storing parent-children like data is going to occur often.
Try this, it will work:
private void button56_Click(object sender, EventArgs e) {
con.Open();
SqlCommand cmd = new SqlCommand("insert into stholidays values('" + dateTimePicker12.Text + "','" + dateTimePicker20.Text + "','" + dateTimePicker13.Text + "','" + mbk + "','" + dateTimePicker14.Text + "','" + dateTimePicker15.Text + "','" + lt + "','" + dateTimePicker16.Text + "','" + dateTimePicker17.Text + "','" + ebk + "','" + dateTimePicker18.Text + "','" + dateTimePicker19.Text + "','" + textBox105.Text + "','" + textBox106.Text + "','" + textBox107.Text + "','" + dd + "','" + textBox104.Text + "')", con);
SqlCommand cmd1 = new SqlCommand("insert into holidays values('" + dd + "','" + ms + "','" + day + "','" + textBox104.Text + "')", con);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
}

Categories