C# 返回单行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11397946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a single row
提问by oshirowanen
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:
但我收到以下错误消息:
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"];
编译器错误消息:CS0266:无法将类型“对象”隐式转换为“字符串”。存在显式转换(您是否缺少演员表?)
第 90 行:return reader["col_1"];
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.
我确定我犯了一个非常明显的错误,但我似乎找不到任何单行示例,我找到的所有示例都是使用while loop.
采纳答案by Matt Whitfield
reader["col_1"]returns object.
reader["col_1"]返回object。
You want something like reader.GetString(reader.GetOrdinal("col_1")).
你想要类似的东西reader.GetString(reader.GetOrdinal("col_1"))。
Edit -> I just wanted to add a note here that, in addition to the concerns others have raised, a SELECT TOPwithout an ORDER BYcan give you random results based on schema changes and/or merry-go-round scans.
编辑 -> 我只是想在这里添加一个注释,除了其他人提出的问题之外,SELECT TOP没有 anORDER BY可以根据架构更改和/或旋转木马扫描为您提供随机结果。
回答by misha
First of all you can use the cast (string)reader["col_1"]. You are probably expecting a string and reader["col_1"]is an object.
首先,您可以使用 cast (string)reader["col_1"]。您可能需要一个字符串并且reader["col_1"]是一个object.
回答by Mahmoud Gamal
Instead of:
代替:
using (reader = command.ExecuteReader())
{
reader.Read();
return reader["col_1"];
}
You need to cast the reader["col_1"]to string, either reader["col_1"].ToString()or reader.GetString(0)like:
你需要转换reader["col_1"]为字符串,要么reader["col_1"].ToString()或reader.GetString(0)类似:
return reader.GetString(0);
回答by MilkyWayJoe
You can use an ifstatement if your query only returns one value
if如果您的查询只返回一个值,您可以使用语句
[...]
string x = string.Empty;
if(reader.Read()) {
// make sure the value is not DBNull
if(DBNull.Value != reader["col_1"]) {
x = reader.GetString(0);
}
}
[...]
回答by yoozer8
The problem is the return type. The method you are in is expecting you to return a string, but reader["col_1"]is an object. I suggest returning reader["col_1"].ToString()or Convert.ToString(reader["col_1"]).
问题是返回类型。您所在的方法期望您返回一个字符串,但它reader["col_1"]是一个对象。我建议返回reader["col_1"].ToString()或Convert.ToString(reader["col_1"])。
回答by lc.
reader["col_1"]returns an object. I assume your function has a return type of string, which is where the error is coming from, it cannot implicitly convert the objectto a string.
reader["col_1"]返回一个object. 我假设您的函数的返回类型为string,这是错误的来源,它不能隐式转换object为 a string。
You probably expect a string returned from col_1 so you can just cast it: (string)reader["col_1"].
您可能期望从 col_1 返回一个字符串,因此您可以将其强制转换:(string)reader["col_1"]。
回答by yan.kun
To me it seems, you don't want a single row, only a single value:
在我看来,您不需要一行,只需要一个值:
SqlConnection sqlConnection = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = "SELECT TOP 1 col_name FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection.Open();
returnValue = cmd.ExecuteScalar();
sqlConnection.Close();
return returnValue.ToString(); //Note you have to cast it to your desired data type
回答by Navid Kianfar
the reader returns object which you should cast it to what you need, in this case a string.
读取器返回对象,您应该将其转换为您需要的对象,在本例中为字符串。
you can use any of this codes :
您可以使用以下任何代码:
return reader.GetString(0);
return reader.GetString(0);
return reader["col_1"].ToString();
return reader["col_1"].ToString();
return Convert.ToString(reader["col_1"]);
return Convert.ToString(reader["col_1"]);
return reader["col_1"] as string;
return reader["col_1"] as string;
but dont forget to close the connection and reader before leaving the function.
但不要忘记在离开该功能之前关闭连接和阅读器。
string ret = reader.GetString(0);
reader.Close();
connection.Close();
return ret;
回答by Adam Houldsworth
This is how I would style (and fix) the code:
这就是我将如何设置(和修复)代码的样式:
using (var connection = new SqlConnection(ConfigurationManager.AppSettings["connection"]))
using (var command = new SqlCommand(@"select top 1 col_1, col_2 from table1", connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
if (reader.Read()) // Don't assume we have any rows.
{
int ord = reader.GetOrdinal("col_1");
return reader.GetString(ord); // Handles nulls and empty strings.
}
return null;
}
}
Using the index reader[]will give you objecttypes, these need casting. However, I hardly touch that style and always favour the slightly more verbose, but more robust use of ordinals and asking for types in a strongly-typed manner.
使用索引reader[]会给你object类型,这些需要转换。然而,我几乎不碰这种风格,总是喜欢稍微冗长但更健壮的序数使用,并以强类型的方式请求类型。
If you only need the value in the first column of the first row, you can use ExecuteScalarinstead, again this returns an object that can be cast and doesn't need a reader:
如果您只需要第一行第一列中的值,则可以ExecuteScalar改用,这将再次返回一个可以强制转换且不需要读取器的对象:
using (var connection = new SqlConnection(ConfigurationManager.AppSettings["connection"]))
using (var command = new SqlCommand(@"select top 1 col_1, col_2 from table1", connection))
{
connection.Open();
var result = command.ExecuteScalar();
return result == null ? "" : (string)result;
}
回答by Ogbonna Vitalis
Follow the following steps to select a single colume, and display them.
按照以下步骤选择单个列,并显示它们。
//create a connection
SqlConnection sqlConnection = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
//open the connection
sqlConnection.Open();
//Your command query string
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT TOP 1 col_name FROM Customers";
//Execute the reader
SqlDataReader result = cmd.ExecuteReader();
result.Read();
//close the connection
sqlConnection.Close();
return result["coiumn_name"].ToString();

