简体   繁体   English

如何使用MySqlDataReader从数据库mySQL检索数据?

[英]How to retrieve data from database mySQL using MySqlDataReader?

I want to retrieve some specific data from tblBranches based to the choice of the user in the combobox (cboBranch.Text), one is the class_name but when I tried to run the program the messagebox shows MySql.Data.MySqlClient.MySqlDataReader , so how can I properly retrieve the data in my database? 我想根据组合框中用户的选择从tblBranches检索一些特定数据(cboBranch.Text),一个是class_name但是当我尝试运行该程序时,消息框显示MySql.Data.MySqlClient.MySqlDataReader ,那么如何如何正确检索数据库中的数据?

query = "SELECT class_name FROM tblBranches WHERE branch_name=@branch";

MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = _order.cboBranch.Text;

MySqlDataReader dr;

con.Open();
dr = cmd.ExecuteReader();

string class_name = dr.ToString();

MessageBox.Show(class_name);

con.Close();

Rather than call the ToString() method, you need to to call the GetString() method passing the zero-based index of the ordinal position of the column in your query, zero in this case because there is only one column in your query. 与调用ToString()方法不同,您需要调用GetString()方法,以传递查询中列序位置的从零开始的索引,在这种情况下为零,因为查询中只有一列。

Before that, you must call the Read() method to advance the reader onto the first or next record and you also need to check the return value because it will return a bool to indicate if another record was found. 在此之前,必须调用Read()方法将阅读器移至第一条或下一条记录,并且还需要检查返回值,因为它将返回bool以指示是否找到了另一条记录。

So replace this line... 所以更换这条线...

string class_name = dr.ToString();

With

string class_name = dr.Read() ? dr.GetString(0) : "Nothing Found";

Or if there could be more than one record returned... 或者,如果返回的记录不止一个...

string class_names = string.Empty;

while (dr.Read())
    class_names = dr.GetString(0) + "\n";

Just an addition: isn't is easier to use ExecuteScalar in case there's only 1 row to expect as a result? 只是补充:如果结果只有1行,使用ExecuteScalar难道不是很容易吗?

Example: 例:

MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = _order.cboBranch.Text;

var class_name = cmd.ExecuteScalar();

if (class_name != null)
{
    //DoSomething with your result here.
}else{
    //Item not found, handle it here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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