返回单行 [英] Returning a single row
问题描述
我正在尝试从数据库返回一行:
I'm trying to return a single row from a database:
using (connection = new SqlConnection(ConfigurationManager.AppSettings["connection"]))
{
using (command = new SqlCommand(@"select top 1 col_1, col_2 from table1", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
reader.Read();
return reader["col_1"];
}
}
}
但是我得到了错误消息:
But I'm getting the following error message:
编译器错误消息:CS0266:无法将类型'object'隐式转换为'string'。存在显式转换(您是否缺少
强制转换?)
第90行:return reader [ col_1];
Compiler Error Message: CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
Line 90: return reader["col_1"];
我确定我犯了一个非常明显的错误,但是我似乎找不到任何单行示例,我发现的所有示例都是使用的多个返回行while循环
。
I'm sure I am making a really obvious mistake, but I can't seem to find any single row examples, all I examples I find are for multiple returned rows using a while loop
.
推荐答案
reader [ col_1]
返回对象
。
您想要类似 reader.GetString(reader .GetOrdinal( col_1))
。
编辑->我只想在此处添加一条注释,已经提出,选择顶部
而没有 ORDER BY
可以根据架构更改和/或快乐地为您提供随机结果-全面扫描。
Edit -> I just wanted to add a note here that, in addition to the concerns others have raised, a SELECT TOP
without an ORDER BY
can give you random results based on schema changes and/or merry-go-round scans.
这篇关于返回单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!