【问题标题】:Get the result of the select statement and put it in the variable. C#获取select语句的结果,放入变量中。 C#
【发布时间】:2014-03-06 01:07:20
【问题描述】:

我有一个从数据库中获取名称的代码。代码如下。

public void Get_lastname()
    {
        string abc = null;
        connstring.Open();
       OleDbCommand get_lastname = new OleDbCommand("SELECT lastname FROM tbltransactionhistory where name LIKE '" + txtname.Text + "'", connstring);
       get_lastname.ExecuteNonQuery();           
       connstring.Close();
     }

我在T-Sql语句中不太好,我想知道我是否可以得到Select语句的结果并将其放入abc变量中?谢谢大家

【问题讨论】:

  • 使用 sqldataadapter 或 sqldatareader。

标签: c# sql .net c#-4.0 ms-access


【解决方案1】:

您可以使用ExecuteScalar() 方法。

另外,不要连接字符串,使用参数。

另外,您可以使用using 结构打开连接以确保它始终正确关闭:

string abc = null;
using (OleDbConnection conn = new SqlConnection(connstring))
{
    conn.Open();
    OleDbCommand get_lastname = new OleDbCommand("SELECT lastname FROM tbltransactionhistory where name LIKE @name", conn);
    get_lastname.Parameters.AddWithValue("@name", txtname.Text);
    abc = (string)get_lastname.ExecuteScalar();
}

【讨论】:

  • 先生,有一件事。代码使用 (OleDbConnection conn = new OleDbConnection(connstring)) 我得到一个错误。我该如何解决这个问题?
  • “'System.Data.OleDb.OleDbConnection.OleDbConnection(string)' 的最佳重载方法匹配有一些无效参数”和参数 1:无法从 'System.Data.OleDb.OleDbConnection' 转换到“字符串”
  • 把你的连接字符串放在上面代码中connstring的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 2015-02-21
  • 1970-01-01
相关资源
最近更新 更多