I'm trying to get product price by using product name. Below is the function I am using.
public int GetProductPrice(string ProductName)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT ProductPrice FROM Products WHERE ProductName ='" + ProductName + "'", cnn);
int price = (int)cmd.ExecuteScalar();
return price;
}
Now I keep getting this error Specified cast is not valid
, and I don't know why. Can someone help me ?
Firstly, you should use parameterized SQL instead of putting the parameter directly into the SQL. Also, you should use a using
statement to close the command - and connection - when you're done. Oh, and create a new SqlConnection
for each operation. So something like:
public int GetProductPrice(string productName)
{
// Quite possibly extract the connection creation into a separate method
// to call here.
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(
"SELECT ProductPrice FROM Products WHERE ProductName = @ProductName",
conn))
{
command.AddParameter("@ProductName", SqlDbType.VarChar)
.Value = productName;
object price = command.ExecuteScalar();
// And you'd do the casting here
}
}
}
Next, we don't know the type of the ProductPrice
field. It could be that you're getting a long
returned, or perhaps it's decimal
. The simplest way to find out is just to use:
object tmp = cmd.ExecuteScalar();
... and then look in the debugger. Also look at the type of the field in the database - that should really tell you what to expect. Have a look at the SqlDbType
enumeration for mappings between the two.
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