string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
cmd.ExecuteScalar(); //this statement return 0
但我想获取用户的 ID?我怎么才能得到它?
你需要SqlDataReader
.
SqlDataReader提供一种从 SQL Server 数据库中读取只进的行流的方法。
string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) {
rd.Read(); // read first row
var userId = rd.GetInt32(0);
}
只需转换返回值:
int userId = (Int32)cmd.ExecuteScalar();
但请注意,如果您的查询返回空结果集,则ExecuteScalar将返回null ,在这种情况下,上面的代码片段将抛出InvalidCastException。
try with select TOP 1 and ExecuteScalar
string sql = "Select TOP 1 UserId From User where UserName='Gheorghe'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
var result = (Int32)cmd.ExecuteScalar();
}
}