I have the following code:
SqlCommand cmd2 = new SqlCommand(
"SELECT ClaimId FROM tblPayment WHERE PaymentId = " + PaymentID.ToString(),
mvarDBConn);
SqlDataReader reader = cmd2.ExecuteReader();
reader.Read();
Int32 ClaimId = reader.GetInt32(0);
reader.Close();
If I run the SELECT statement in SQL it returns the number fine, but when I use ExecuteReader all it returns is 0. I've tried multiple methods including ExecuteScalar, ExecuteNonQuery, reader.GetString then casting that to an int, etc.
What am I missing? Thanks.
EDIT: Here's what I get in the SQL Server Profile:
Here's what I get back:
exec sp_executesql N'SELECT ClaimId FROM tblPayment WHERE PaymentId = @paymentID',N'@paymentID nvarchar(5)',@paymentID=N'8392'
Have no idea why it's putting it into an SP_ExecuteSQL when the previous SqlCommand I have goes straight to SQL, same with the 'N's.
Better to use SqlCommand.ExecuteScalar()
for this:
int ClaimId = Convert.ToInt32(cmd2.ExecuteScalar());
Also, to avoid a possible SQL Injection attack , use ADO Command Object with Parameters:
// create command
SqlCommand cmd2 = new SqlCommand(
"SELECT ClaimId FROM tblPayment WHERE PaymentId = @paymentID",
mvarDBConn);
// add parameter
cmd2.Parameters.AddWithValue("@paymentID", PaymentID);
// execute command and convert the result
int ClaimId = Convert.ToInt32(cmd2.ExecuteScalar());
You can try with
new SqlCommand("SELECT ClaimId FROM tblPayment WHERE PaymentId = @param");
And
cmd2.Parameters.AddWithValue("@param", PaymentID);
Try to run a while loop on the read.
while (reader.Read())
{
Int32 ClaimId = reader.GetInt32(0);
}
Although, you might want to declare the ClaimId variable outside the while.
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.