SQL Server INSERT command does not insert data
I want to insert the content of some text fields into a SQL Server database.
This is the code I'm using:
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
SqlCommand InsertCommand = new SqlCommand("INSERT INTO invmgmt.Products (product_id, product_name, product_price, possible_discount, product_in_stock) VALUES ('" + Convert.ToInt32(tbAddProdID.Text) + "','" + tbAddProdName.Text + "','" + Convert.ToDouble(tbAddProdPrice.Text) + "','" + Convert.ToInt32(tbAddPblDiscount.Text) + "','" + Convert.ToInt32(tbAddInStock.Text) + "')");
myConn.Close();
If I execute this, nothing happens to the database, does anyone know what to do? I've tried some other commands Insert
but nothing wants to work.
+3
source to share
6 answers
You need to bind the connection to your command, then execute your request:
InsertCommand.Connection = conn; InsertCommand.ExecuteNonQuery();
Several other things:
- Don't use string concatenation to create a SQL query. Use the parameters with your request. See SqlCommand.Parameters otherwise you are prone to SQL injection
- Close your connection object and commands in
using
.
+8
source to share
add the connection to your command and execute it:
SqlCommand InsertCommand = new SqlCommand("INSERT INTO invmgmt.Products (product_id, product_name, product_price, possible_discount, product_in_stock) VALUES ('" + Convert.ToInt32(tbAddProdID.Text) + "','" + tbAddProdName.Text + "','" + Convert.ToDouble(tbAddProdPrice.Text) + "','" + Convert.ToInt32(tbAddPblDiscount.Text) + "','" + Convert.ToInt32(tbAddInStock.Text) + "')",myConn);
InsertCommand.ExecuteNonQuery();
+1
source to share
After that you have to execute the request and close your connection as shown below.
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
string sql ="YOUR QUERY...";
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
SqlCommand InsertCommand = new SqlCommand(sql,myConn);
InsertCommand.ExecuteNonQuery();
myConn.Close();
or if you want to check if the request is being executed or not, instead.
if(InsertCommand.ExecuteNonQuery()>0){ //some message or function }
the return value is the number of rows affected by the operator.
0
source to share