I've tried lots of suggestions on the Internet in order to run executeScalar
, but I get the error ExecuteScalar: Connection property has not been initialized
. My INSERT
query is working fine, the problem is with executeScalar
.
conn.Open();
SqlCommand cmd = new SqlCommand(
"INSERT INTO Products (Product_Name,Product_BarCode,Product_CP,Product_SP,
Product_Countainer,Product_Pcs,Product_MFGDate,
Product_ExpiryDate,Product_Grade)
Values ('" + Name.Text + "','" + BarCode.Text + "','" + CostP.Value + "','" +
SellingP.Value + "','" + Countainer.Value + "','" + Pcs.Value + "','" +
MfgDate.Value + "','" + ExpDate.Value + "','" + Grade.SelectedItem + "')",
conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
cmd.Connection = conn;
cmd = new SqlCommand("SELECT SUM(Product_CP) FROM Products AS Amount");
Amount = (double)cmd.ExecuteScalar();
MessageBox.Show(Amount.ToString());
conn.Close();
ExecuteScalar: Use this operation to execute any arbitrary SQL statements in SQL Server to return a single value. This operation returns the value only in the first column of the first row in the result set returned by the SQL statement.
ExecuteScalar method is used to execute SQL Commands or storeprocedure, after executing return a single value from the database. It also returns the first column of the first row in the result set from a database.
No, you need to explicitly open and close the connection when using ExecuteScalar(). Save this answer.
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
cmd = new SqlCommand(...);
As the error clearly states, this command doesn't have a connection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With