SQL Exception in run time

Viewed 54

I am trying to add values to a database using WPF form.

This is my code:

private void Insertbtn_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source=DESKTOP-HSIK0SQ; Initial Catalog=Demo; Integrated Security=SSPI");
    conn.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
    
    int count = cmd.ExecuteNonQuery();

    MessageBox.Show(count + " record saved successfully");

    conn.Close();
}

When I am hitting the insert button:

WPF form

This is the exception being thrown:

Exception

I am sure that whichever the labels and text boxes I have added they have unique name in the property. It is throwing exception while executing the query command

I am not sure what I could miss here?

1 Answers

Make sure to surround these values with single quotes '', and if these variables are the TextBoxes, then you have to call .Text on them to get the proper values..

cmd.CommandText = "Insert into Student values ('"+ RollNumebrtxt.Text + "','" + FNametxt.Text + "','" +
        Coursetxt.Text + "');";

Better to parametrised your query..

Replace

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";

With

SqlCommand cmd = new SqlCommand("INSERT INTO Student VALUES(@RollNumber, @FName, @CourseName)", conn);
cmd.Parameters.Add("@RollNumber", SqlDbType.Int).Value = int.Parse(RollNumebrtxt.Text);
cmd.Parameters.Add("@FName", SqlDbType.VarChar, 100).Value = FNametxt.Text;
cmd.Parameters.Add("@CourseName", SqlDbType.VarChar, 100).Value = Coursetxt.Text;
Related