如何使用SQL查询结果中的变量?

时间:2019-04-06 23:39:50

标签: c# sql-server

我想同时在变量中使用sql查询结果。我该怎么办?

var conn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB; AttachDbFileName=|DataDirectory|database.mdf;");
conn.Open();
var comm = new SqlCommand($"SELECT name FROM database WHERE age = 25", conn);
var reader = comm.ExecuteReader();
 while(reader.Read())
{
  string name =reader[0].ToString();

}
conn.Close();


if (name != textbox.Text)
{
 //do something
}

2 个答案:

答案 0 :(得分:1)

使用DataTable,您可以轻松访问行数据。像这样:

DataTable dt = new DataTable();
dt.Load(reader)

然后,您可以使用DataTable.Rows属性。

DataRow row = dt.Rows[0];
string name = row["name"].ToString();

答案 1 :(得分:0)

您可以改用DataAdapter:

var table = new DataTable(); 

using(SqlConnection con = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB; AttachDbFileName=|DataDirectory|database.mdf;"))
using(SqlCommand command =  new SqlCommand($"SELECT name FROM database WHERE age = 25", con))
using(SqlDataAdapter adapter = new SqlDataAdapter(command))
{
    con.Open();
    adapter.Fill(table);
}


// if single row 
if (table.Rows[0].Field<string>("name") != textbox.Text)
{
 //do something
}

//if multiple rows 
for(int x = 0; x < table.Rows.Count; x++)
{
    if (table.Rows[x].Field<string>("name") !=  textbox.Text)
    {
     //do something
    }
}