Your code is a giant example of a
SQL Injection Vulnerability
NEVER EVER create an SQL command by concatenating a bunch of commands and user input.
The correct way to add values into a query is going to be by using the
SQL Parameter Collection
. This will properly escape any funky characters going on and will also add it in as to whatever data-types you have in your NET project... so you wont need to worry about added single quotes in for text etc.
A few minute rewrite of your source code gave me something like this
private void button2_Click(object sender, EventArgs e)
{
con.Open();
string qry = "INSERT INTO record VALUES (@t1, @t2, @t3, @Sn, @Sn1, @Mn, @Mn1, @Tu, @Tu1, @Wd, @Wd1, @Th, @Th1, @Fr, @Fr1, @St, @St1)";
cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("@t1", textBox1.Text);
cmd.Parameters.AddWithValue("@t2", textBox2.Text);
cmd.Parameters.AddWithValue("@t3", textBox3.Text);
cmd.Parameters.AddWithValue("@Sn", sun.Text);
cmd.Parameters.AddWithValue("@Sn1", sun1.Text);
cmd.Parameters.AddWithValue("@Mn", mon.Text);
cmd.Parameters.AddWithValue("@Mn1", mon1.Text);
cmd.Parameters.AddWithValue("@Tu", tue.Text);
cmd.Parameters.AddWithValue("@Tu1", tue1.Text);
cmd.Parameters.AddWithValue("@Wd", wed.Text);
cmd.Parameters.AddWithValue("@Wd1", wed1.Text);
cmd.Parameters.AddWithValue("@Th", thur.Text);
cmd.Parameters.AddWithValue("@Th1", thur1.Text);
cmd.Parameters.AddWithValue("@Fr", fri.Text);
cmd.Parameters.AddWithValue("@Fr1", fri.Text);
cmd.Parameters.AddWithValue("@St", sat.Text);
cmd.Parameters.AddWithValue("@St1", sat1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data is save now in Database");
}
And low and behold, I do see the syntax error you got most likely was due to the confusion of single & double quotes codgered together
insert into record values (
'" + textBox1.Text +"'
, '" + textBox2.Text +"'" + "
, '" + textBox3.Text +"'
, '" + sun.Text +"
, " + sun1.Text +"'
Now that we got rid of the vulnerability which also fixes your syntax error; I do see a few problems that I see in your code.
You open the SQL Connection in the routine, but do not close this. This can actually fail if the connection is already open.
Likewise, you define an existing SQL command and execute it. Generally this should be created and destroyed within the routine.
Your message box appears if no exceptions are thrown, which may be fine in this case; but if it was a claused-update statement it would still work even if no rows were updated.
Generally I would wrap this within an
IF...ELSE
block to give a little better feedback.
int ra = cmd.ExecuteNonQuery();
if (ra == 1) {
MessageBox.Show("Data is save now in Database");
} else {
MessageBox.Show("There was a problem saving your data.");
}
Reference:
SqlParameterCollection.AddWithValue(String, Object) Method (System.Data.SqlClient) | Microsoft Docs[
^]