Search code examples
c#sql-serverwinformsado.netsql-insert

How to insert data to a database in C#


I've just started to learn about databases and actually I've no idea why the code below doesn't work. I have searched a lot but I didn't realized what exactly is the happening.

I have a Windows Forms app and there are a textbox and a button in it. When I click on the button, the text inside the textbox should get inserted into the database, but nothing is actually happening.

I created the database with Visual Studio. I right-clicked on "Data connections" in Server Explorer in Visual Studio 2019 Community edition and then clicked on "Create New SQL Server Database".

using (SqlConnection con = new SqlConnection("Data Source = (localdb)\\mssqllocaldb; Initial Catalog = myTestDB; Integrated Security = True; Pooling = False")) 
{
    con.Open();

    SqlCommand cmd = new SqlCommand("INSER INTO [tesTable] VALUES (@fname, @lname)", con);

    cmd.Parameters.AddWithValue("@fname", textBox1.Text);
    cmd.Parameters.AddWithValue("@lname", textBox2.Text);
}

MessageBox.Show("done!");

Solution

  • Because you haven't executed your command:

    ....
    cmd.Parameters.AddWithValue("@lname", textBox2.Text);
    
    cmd.ExecuteNonQuery();
    

    The fixed version of your insert statement should be something like this:

    "INSERT INTO tesTable (fname,lname) VALUES (@fname,@lname)"
    

    This also needs to be added, that specifying the type directly and use the Value property is more better than AddWithValue:

    cmd.Parameters.Add("@lname", SqlDbType.VarChar).Value = textBox2.Text;
    

    Can we stop using AddWithValue() already?