简体   繁体   中英

Query Sql to return value

I want to write Query to display value in MessageBox , but it is not true :

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

You would need to do this:

myReader.GetString(0);

However, there is a bit more that needs done here. You need to leverage the ADO.NET objects properly:

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));
}
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();

When you just want one return value, you can use ExecuteScalar() like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM