C# 如何访问SQL中的第一列,为什么这段代码会给我错误?
有人能告诉我为什么我的C# 如何访问SQL中的第一列,为什么这段代码会给我错误?,c#,sql-server,C#,Sql Server,有人能告诉我为什么我的expectedNumber阅读器出错吗 名称读取器在其当前上下文中不存在 据我所知,这一切都是在阅读第一行和第一列,我不明白为什么读者会发脾气 它不喜欢这句台词: ExpectedNumber = reader.GetInt16(0); 查询是: SELECT TOP (1) [ExpectedNumber] FROM [dbo].[MyDatabase] WHERE id = '{0}' 代码: 您应该转义查询参数,否则您的代码容易受到SQL注入攻击。此外,通过
expectedNumber
阅读器出错吗
名称读取器在其当前上下文中不存在
据我所知,这一切都是在阅读第一行和第一列,我不明白为什么读者会发脾气
它不喜欢这句台词:
ExpectedNumber = reader.GetInt16(0);
查询是:
SELECT TOP (1) [ExpectedNumber]
FROM [dbo].[MyDatabase]
WHERE id = '{0}'
代码:
您应该转义查询参数,否则您的代码容易受到SQL注入攻击。此外,通过使用下面示例中的命令参数,您可以确保使用了正确的数据类型(似乎您正在尝试以字符串形式传递int id) 您只是试图获取一个值,因此不需要使用读卡器,而是可以使用
ExecuteScalar
最后,如果将连接包含在using块中,则不需要处理关闭连接的问题,这样也可以避免try-catch块
string query = "SELECT TOP (1) [ExpectedNumber] FROM [dbo].[MyDatabase] WHERE id = @id";
using (var connection = new SqlConnection("connStr"))
{
connection.Open();
using (var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
object result = cmd.ExecuteScalar();
if (result != null && result.GetType() != typeof(DBNull))
{
return (int)result;
}
Assert.Fail("No Results Returned from Expected Result Query");
return 0;
}
}
注意:此代码假定您使用的是SQL Server,对于其他系统,连接字符串中参数的格式可能会更改,例如,对于Oracle,它应该是
:id
而不是@id
您是否也可以包含查询?您的意思是您得到了编译时错误CS0103当前上下文中不存在名称“reader”
?这对于上面的代码没有意义。但是,我希望上面的代码为编译时错误CS0103提供名称“ExpectedResult”在当前上下文中不存在
,因为您返回的是ExpectedResult,而它看起来像是ExpectedNumber。如果Id
是主键,为什么需要TOP(1)
?不要使用我认为在带有INT参数的select语句上使用AddWithValue没有任何问题,但我还是对其进行了更改。
string query = "SELECT TOP (1) [ExpectedNumber] FROM [dbo].[MyDatabase] WHERE id = @id";
using (var connection = new SqlConnection("connStr"))
{
connection.Open();
using (var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
object result = cmd.ExecuteScalar();
if (result != null && result.GetType() != typeof(DBNull))
{
return (int)result;
}
Assert.Fail("No Results Returned from Expected Result Query");
return 0;
}
}