繁体   English   中英

使用C#的SELECT语句

[英]SELECT statement using C#

我有以下代码:

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();

如果我在SQL中运行SELECT语句,它返回的数字很好,但是当我使用ExecuteReader时,它返回的都是0。我尝试了多种方法,包括ExecuteScalar,ExecuteNonQuery,reader.GetString,然后将其转换为int等。

我想念什么? 谢谢。

编辑:这是我在SQL Server配置文件中得到的:

这是我得到的:

 exec sp_executesql N'SELECT ClaimId FROM tblPayment WHERE PaymentId = @paymentID',N'@paymentID nvarchar(5)',@paymentID=N'8392'

不知道为什么当我之前的SqlCommand直接转到SQL(与'N'相同)时,为什么将其放入SP_ExecuteSQL。

最好为此使用SqlCommand.ExecuteScalar()

int ClaimId = Convert.ToInt32(cmd2.ExecuteScalar());

另外,为避免可能的SQL注入攻击 ,请使用带参数的ADO命令对象:

// 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());

您可以尝试

 new SqlCommand("SELECT ClaimId FROM tblPayment WHERE PaymentId = @param"); 

 cmd2.Parameters.AddWithValue("@param", PaymentID);

尝试对读取运行while循环。

while (reader.Read())
{
    Int32 ClaimId = reader.GetInt32(0);
}

虽然,您可能想在while之外声明ClaimId变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM