I am trying to insert a record if requested prodName
doesnot exist in database. If it exists I want to update the value of quantity
attribute. I have used the following it neither inserts nor Updates any record. I get following exception:
ExecuteScalar requires an open and available Connection. The connection's current state is closed
This is the code
public static void manageStock(CompanyStock stock)
{
///// Check if record exists/////////
cmd = new SqlCommand("select count(*) from tblStock where prodName=@prodName", con);
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar(); //returns null if doesnt exist
con.Close();
if (count > 0)
{
cmd = new SqlCommand("update tblStock set quantity = @quantity where prodName=@prodName", con);
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
cmd.Parameters.AddWithValue("@quantity", stock.quantity);
}
else
{
cmd = new SqlCommand("insert into tblStock(prodName,quantity) values (@prodName, @quantity)", con);
cmd.Parameters.AddWithValue("@prodName",stock.prodName);
cmd.Parameters.AddWithValue("@quantity",stock.quantity);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
Edited
I edited my code. It works fine now. I had to open my connection before executing ExecuteScalar
But I want to know the standard way of writing this opening and closing stuff. It looks kind of haphazard. How can I improve this?