Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteScalar: Connection property has not been initialized

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();
like image 349
alternatefaraz Avatar asked Dec 04 '12 19:12

alternatefaraz


People also ask

What does ExecuteScalar mean?

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.

What is ExecuteScalar method in Ado net?

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.

Does ExecuteScalar close connection?

No, you need to explicitly open and close the connection when using ExecuteScalar(). Save this answer.

Under which scenario do you need ExecuteScalar method?

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.


1 Answers

cmd = new SqlCommand(...);

As the error clearly states, this command doesn't have a connection.

like image 99
SLaks Avatar answered Sep 25 '22 00:09

SLaks