Reputation:
I want to insert the content of some textboxes into a SQL Server database.
This is the code I use:
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 that, nothing happens to the database, does anyone know what to do? I've tried some other Insert
commands, but nothing wants to work.
Upvotes: 3
Views: 791
Reputation: 19
You have to execute the query and close your connection after this 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 query is executed or not do this instead.
if(InsertCommand.ExecuteNonQuery()>0){ //some message or function }
the returned value are the number of rows affected by the statement.
Upvotes: 0
Reputation: 81
ExecuteNonQuery() return the number of rows affected, so its better to check the return to handle error condition
Int32 ret = sqlcommand.ExecuteNonQuery();
if (ret <= 0)
{
enter code here
}
Upvotes: 0
Reputation: 650
after opening connection try code below:
string query = ..........;
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.ExecuteNonQuery();
myConn.Close();
Note: type your query instead of dots.
Upvotes: 0
Reputation: 223187
You have to associate a connection with your command then execute your query:
InsertCommand.Connection = conn;
InsertCommand.ExecuteNonQuery();
Few other things:
using
statement. Upvotes: 7
Reputation: 14389
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();
Upvotes: 1