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:

+8


source


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


You are missing:

InsertCommand.ExecuteNonQuery();

      

+1


source


after opening the connection, try the code below:

string query = ..........;
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.ExecuteNonQuery();
myConn.Close();

      

Note: enter your query instead of dots.

0


source


ExecuteNonQuery () returns the number of rows affected, so it is better to check the return to handling the error condition

Int32 ret = sqlcommand.ExecuteNonQuery ();

if (ret <= 0) { enter code here

}

0


source


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







All Articles