How to parameterize SQL for INSERT?

117 Views Asked by At

I have tried the code below but my SQL table is empty and there was no error message. Below is my code:

private void button1_Click(object sender, EventArgs e)
{
        string mainconn = ConfigurationManager.ConnectionStrings["Delivery_Inspection.Properties.Settings.TransitiondayConnectionString"].ConnectionString;

        SqlConnection sqlconn = new SqlConnection(mainconn);

        String query = "INSERT INTO Table1 (Busnumber, Remarks, Dt1check1) VALUES (@bn, @rm, @dt1)";

        using (SqlCommand command = new SqlCommand(query, sqlconn))
        {
            command.Parameters.AddWithValue("@bn", label1.Text.ToString());
            command.Parameters.AddWithValue("@rm", richTextBox1.Text.ToString());
            command.Parameters.AddWithValue("@dt1", this.dataGridView1[1, 0].Value);

            sqlconn.Open();
            int result = command.ExecuteNonQuery();

            // Check Error
            if (result < 0)
                Console.WriteLine("Error inserting data into Database!");
        }
}
1

There are 1 best solutions below

7
tgralex On

Try to move sqlconn.Open(); before you create command and execute it

and I suggest to put it in uses as well:

 private void button1_Click(object sender, EventArgs e)
    {
        var mainconn = ConfigurationManager.ConnectionStrings["Delivery_Inspection.Properties.Settings.TransitiondayConnectionString"].ConnectionString;
        using (var sqlconn = new SqlConnection(mainconn))
        {
            sqlconn.Open();
            var query = "INSERT into Table1(Busnumber,Remarks,Dt1check1)VALUES (@bn,@rm,@dt1)";
            using (var command = new SqlCommand(query, sqlconn))
            {
                command.Parameters.AddWithValue("@bn", label1.Text.ToString());
                command.Parameters.AddWithValue("@rm", richTextBox1.Text.ToString());
                command.Parameters.AddWithValue("@dt1", this.dataGridView1[1, 0].Value);
                var result = command.ExecuteNonQuery();

                // Check Error
                if (result < 0)
                    Console.WriteLine("Error inserting data into Database!");
            }
        }
    }