C#如何执行字符串然后存储结果?

时间:2017-07-27 13:32:51

标签: c# sqlconnection

作为参考,此页面(add.ashx.cs)是数据库的添加页面。

我要做的是:

  1. 弄清楚如何执行字符串queryID,然后
  2. 存储queryID的结果
  3. 我对此有点新意,但这是我到目前为止所做的工作。我是在正确的道路上,我应该改变什么?我不相信下面的代码包括存储结果,而只是执行queryID。

    // new query to get last ID value
    // store the command.executeNonQuery results into a variable
    
    string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
    // first: look up how to execute queryID
    // then: store results of query ^
    
    // execute queryID? (section below)
    SqlConnection sqlConnection1 = new SqlConnection(queryID);
    SqlCommand cmd = new SqlCommand();
    SqlDataReader reader;
    cmd.CommandText = "Select * FROM queryID";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlConnection1;
    
    sqlConnection1.Open();
    
    reader = cmd.ExecuteReader();
    // data is accessible through the datareader object here
    
    sqlConnection1.Close();
    

1 个答案:

答案 0 :(得分:3)

您的代码示例中存在一些不匹配的内容。第一个queryID是您的实际查询。在SqlConnection中,您需要提供连接到数据库的连接字符串(SQL Server,ACCESS,...)。一个有效的例子可能如下所示:

    // this is just a sample. You need to adjust it to your needs
    string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
    SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
    SqlCommand cmd = new SqlCommand(sqlConnection1 );
    SqlDataReader reader;

    cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
    cmd.CommandType = CommandType.Text;
    sqlConnection1.Open();

    reader = cmd.ExecuteReader();

    List<string> results = new List<string>();

    if(reader.HasRows)
    {
        while(reader.Read())
        {
            results.Add(reader[0].ToString());
        }
    }

    sqlConnection1.Close();

另一件事是,您执行一个阅读器但只选择一个值。您可以完美地使用ExecuteScalar

// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );

cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();

string result = cmd.ExecuteScalar().ToString();

sqlConnection1.Close();

最后一件事。您应该在using块中使用实现IDisposable的对象。这样,当不再需要它们时,它将从内存中删除:

// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
    SqlCommand cmd = new SqlCommand(sqlConnection1 );

    cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
    cmd.CommandType = CommandType.Text;
    sqlConnection1.Open();

    string result = cmd.ExecuteScalar().ToString();
}