我的大多数查询都很短,共有1-3条记录。这是我现在的代码。我想知道是否有办法直接从DataAdapter捕获userid而不通过表。谢谢!
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable t = new DataTable();
dataAdapter.Fill(t);
int userid = 0;
if (t.Rows.Count > 0)
{
DataRow dr = t.Rows[0];
userid = dr.Field<int>(0);
答案 0 :(得分:4)
如果您只有一个返回值,则可以使用ExecuteScalar并ExecuteReader获取多个返回值。
这是msdn示例:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
答案 1 :(得分:2)