选择语句的返回值 [英] Return value of a select statement

查看:31
本文介绍了选择语句的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 select 语句的结果值检索到字符串变量中.像这样:

I want to retrieve the resulting value of a select statement into a string variable. Like this:

OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
        

我想将选定的治疗值放入字符串变量中.我该怎么做?

I want to place the selected treatment value into a string variable. How can I do this?

推荐答案

使用 ExecuteReader() 而不是 ExecuteNonQuery().ExecuteNonQuery() 仅返回受影响的行数.

Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.

try
{
    SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{

}
while(dr.Read())
{
    string treatment = dr[0].ToString();
}

或者更好,使用 using 声明 因为它.

Or better, use a using statement for it.

using(SqlDataReader dr = cmd1.ExecuteReader())
{
    while(dr.Read())
    {
        string treatment = dr[0].ToString();
    }
}

但如果您的 SqlCommand 仅返回 1 列,您可以使用 ExecuteScalar() 方法.它返回第一行的第一列,如下所示:-

But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-

cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());

您也可以打开您的代码以SQL 注入.始终使用参数化查询.Jeff 有一篇很酷的博客文章,名为 给我参数化的 SQL,否则给我死.请仔细阅读.另请阅读 DotNetPerl SqlParameter 文章.SQL 注入在您处理查询时非常重要.

Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.

这篇关于选择语句的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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