从SQL检索的ExecuteScalar值() [英] Retrieving value from sql ExecuteScalar()

查看:316
本文介绍了从SQL检索的ExecuteScalar值()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

String sql = "SELECT * FROM Temp WHERE Temp.collection  = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
Program.defaultCollection = (String)cmd.ExecuteScalar();

和我要执行该语句后拿到的第二列。我知道这将返回只有一排有两列

And I want to get the second column after executing the statement. I know it will return only one row with two columns

我看了网上说我将不得不读取结果中的每一行,还有没有别的办法?

I have read online that I will have to read each row of the result, is there any other way?

推荐答案

的ExecuteScalar 会从结果集的第一行的第一列。如果你需要访问不止这些,你就需要采取不同的方法。像这样的:

ExecuteScalar gets the first column from the first row of the result set. If you need access to more than that you'll need to take a different approach. Like this:

DataTable dt = new DataTable();
SqlDataAdapater sda = new SqlDataAdapter(sql, conn);
sda.Fill(dt);

Program.defaultCollection = dt.Rows[0]["defaultCollection"];

现在,我才知道的字段名称可能不是 defaultCollection ,但你可以填写在

Now, I realize that the field name may not be defaultCollection, but you can fill that in.

从的的ExecuteScalar MSDN文档

From the MSDN documentation for ExecuteScalar:

执行查询,并在由该查询返回的结果集返回第一行的第一列。其他列或行被忽略。

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.

现在,作为建议的最后一点,请包装在所有的ADO.NET对象使用语句。像这样的:

Now, as a final bit of advice, please wrap all ADO.NET objects in a using statement. Like this:

using (SqlConnection conn = new SqlConnection(connString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
{
   DataTable dt = new DataTable();
   sda.Fill(dt);

   // do something with `dt`
}



这将确保他们得到妥善处置。

this will ensure they are properly disposed.

这篇关于从SQL检索的ExecuteScalar值()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆