如何从数据库中获取一个简单的字符串
下面的代码不起作用。该表中只有 1 行。我如何获得 sql 将返回的语句?:
SqlConnection conn = new SqlConnection(connectionStringArg);
SqlCommand command = new SqlCommand("select applicationname from tbl_settings");
command.Connection = conn;
conn.Open();
string simpleValue = command.ExecuteReader()[0].ToString();
conn.Close();
return simpleValue;
好的,任何有关如何实现这个相对简单的任务的帮助都会很棒。
The following code does not work. There is only 1 row in this table. How do I just get the statement that the sql would return?:
SqlConnection conn = new SqlConnection(connectionStringArg);
SqlCommand command = new SqlCommand("select applicationname from tbl_settings");
command.Connection = conn;
conn.Open();
string simpleValue = command.ExecuteReader()[0].ToString();
conn.Close();
return simpleValue;
Okay any help on how to achieve this relatively simple task would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
由于只返回一个值,您可以这样做:
如果您需要返回的第一行中的第一列以上的值,则需要使用 ExecuteReader()。请参阅 driis 的答案。
Since there's only a single value returned, you could do this:
If you need more than the first column from the first row returned, you'll need to use ExecuteReader(). See driis' answer.
DataReader 不能这样索引。您需要类似的东西:
总体思路是推进每条记录的读取器(使用
Read
),然后您可以从该行读取值。正如另一个答案中所指出的,如果您知道结果集中只有一个值,command.ExecuteScalar() 就会为您提供这一点。The DataReader can't be indexed like that. You need something like:
The general idea is to advance the reader for each record (using
Read
), then you can read values from the row. As pointed out in another answer, if you know there is only one single value in the result set,command.ExecuteScalar()
gives you just that.您必须在从 ExecuteReader 返回的 DataReader 上调用
Read
方法才能到达第一行。像这样的东西:You have to call the
Read
method on a DataReader returned from ExecuteReader to get to the first row. Something like this:你会做例如
You'd do e.g.
对于要使用的单个字符串 ExecuteScalar< /a> 获取单个值,然后尝试将其转换为字符串。
From doc: 执行查询,并返回查询返回的结果集中第一行的第一列。附加的列或行将被忽略。
示例:
string result = command.ExecuteScalar() as string;
对于小东西,我经常发现 LINQ2SQL 最容易设置和使用。 本教程 应该可以让您在几分钟内启动并运行。对于较大的项目LINQ2SQL 已被视为已过时 ,请参阅此问题进行讨论和替代方案。
For a single string you want to use ExecuteScalar to get a single value and then attempt to cast it to string.
From doc: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Example:
string result = command.ExecuteScalar() as string;
For small stuff I often find LINQ2SQL the easiest to set up and use. This tutorial should get you up and running in a few minutes. For bigger projects LINQ2SQL is considered obsolete, see this question for discussion and alternatives.
检查 DataReader.Read()需要调用它。
Check DataReader.Read() you need to call it.