查询Sql以返回值

时间:2013-11-19 14:12:03

标签: c# sql sqldatareader

我想编写Query以在MessageBox中显示值,但事实并非如此:

SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
myReader = myCommand.ExecuteReader();
MessageBox.Show(myReader.ToString());
cn.Close();

3 个答案:

答案 0 :(得分:1)

你需要这样做:

myReader.GetString(0);

然而,这里需要做的更多。您需要正确利用ADO.NET对象:

var sql = "select BillNumber from BillData";
using (SqlConnection cn = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand(sql, cn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
    rdr.Read();
    MessageBox.Show(rdr.GetString(0));
}

答案 1 :(得分:0)

SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
myReader = myCommand.ExecuteReader();
myReader.Read();
MessageBox.Show(myReader["BillNumber"].ToString());
cn.Close();

答案 2 :(得分:0)

如果您只想要一个返回值,可以像这样使用ExecuteScalar()

SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
string return_value = myCommand.ExecuteScalar().ToString();
MessageBox.Show(return_value);
cn.Close();