-2

executenonquery() error c# this is how my code looks like

con.Open();

String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();

String id = textBox3.Text.ToString();
int iid = Int32.Parse(id);

String semester = textBox4.Text.ToString();
int i_sem = Int32.Parse(semester);

String field = comboBox1.SelectedItem.ToString();

String qry = "insert into Table values('" + name + "','" + address + "'," + iid + "," + i_sem + ",'" + field + "',)";

SqlCommand cmd = new SqlCommand(qry, con);

cmd.ExecuteNonQuery();

executenonquery() always makes me problem !

int i = cmd.ExecuteNonQuery();
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
Hatemii
  • 39
  • 3

1 Answers1

1

You need to fix a couple of things:

  1. Remove the last , in your query.
  2. I don't know if you have a table named Table in your database but you should check if the name is correct.
  3. When you don't know how to correct your code it's better use the try-catch statement to understand where the real problem is in your code. Here is an example about how to handle SQL exception in C# code.
  4. You are getting SqlException because your query syntax is wrong but there is another way to add SQL parameters into your query without need to use a string variable. You could use the SqlParameterCollection.AddWithValue(String, Object) method to achieve the same result and avoid SQL Injection:
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into YourTableName (name, address, id, semester, field) VALUES (@name, @address, @id, @semester, @field)";
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@address", address);
command.Parameters.AddWithValue("@id", iid);
command.Parameters.AddWithValue("@semester", i_sem);
command.Parameters.AddWithValue("@field", field);

try
{
    connection.Open();
    int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
    // error here
}
finally
{
    connection.Close(); //close your connection if you do not need to keep it open
}

More info: