con = new SqlConnection (cs);
SqlCommand UpdateCommand = new SqlCommand("Update Stock Set ConfigID = @ConfigID , Quantity = @Quantity ,TotalPrice =@TotalPrice, StockDate =@StockDate ,Where StockID='" +txtStockID.Text+"'");
UpdateCommand.Parameters.Add("@ConfigID",SqlDbType.Int).Value= txtConfigID.Text;
UpdateCommand.Parameters.Add("@Quantity", SqlDbType.Int).Value = txtQty.Text;
UpdateCommand.Parameters.Add("@TotalPrice", SqlDbType.Int).Value = txtTotalPrice.Text;
UpdateCommand.Parameters.Add("@StockDate", SqlDbType.NVarChar, 50).Value = dtpStockDate.Value;
con.Open();
UpdateCommand.ExecuteNonQuery();
con.Close();
I find this error-message understandable, isn't it? However, you have to assign the connection to the SqlCommand
, either by using the constructor or the property Connection
:
string updateSQL = @"UPDATE Stock Set ConfigID = @ConfigID,
Quantity = @Quantity,
TotalPrice = @TotalPrice,
StockDate = @StockDate
WHERE StockID = @StockID";
SqlCommand UpdateCommand = new SqlCommand(updateSQL, con);
or
SqlCommand UpdateCommand = new SqlCommand(updateSQL);
UpdateCommand.Connection = con;
StockID
in the Where
and removed the last comma before the Where
. Note also that you should close connections when you're finished, therefore you can use the using
-statement which ensures that it gets disposed/closed even on error:
using(var con = new SqlConnection (cs)) { // ... }
how to solve error of “ ExecuteNonQuery: Connection property has not been initialized?”
By initializing the Connection
property
UpdateCommand.Connection = con;
UpdateCommand.ExecuteNonQuery();
Also you should wrap your connection object with a using statement to make sure it is properly disposed.
You can also use the connection to create the command:
var command = connection.CreateCommand();
This ensures you have a command initialised with the correct connection. You can set the query string using the property command.CommandText
:
command.CommandText = @"SELECT foo FROM foo";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.