-3

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?

ASh
  • 34,632
  • 9
  • 60
  • 82
Mr. A
  • 103
  • 1
  • 2
  • 17
  • 1
    **Parametrise** your code. Your application is wide upon to injection attacks and writing good, secure code will also solve the problem you are encountering. – Thom A Sep 18 '22 at 12:54
  • This is just for practice.. do yo solution for the problem I stated? – Mr. A Sep 18 '22 at 13:14
  • 1
    [Why do we always prefer using parameters in SQL statements?](https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements) – Thom A Sep 18 '22 at 13:15
  • I understand that but, is that the solution to above problem? – Mr. A Sep 18 '22 at 13:20
  • 1
    Yes, the solutions is to use parameters, **always**. Side note: your connection and command objects need `using` to dispose them – Charlieface Sep 18 '22 at 13:32
  • As I said, writing good, secure code will resolve the problem too. If you *parametrise* your code you won't get the SQL syntax error you are getting. – Thom A Sep 18 '22 at 13:33

1 Answers1

2

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;
Charlieface
  • 52,284
  • 6
  • 19
  • 43
Muhammad Sulaiman
  • 2,399
  • 4
  • 14
  • 28