我不熟悉使用Data Reader,我需要以下代码的帮助,我想从数据库中检索单个数据.
I'm not familiar with using Data Reader, i need help with the following code, i want to retrieve a single data from the database.
MySqlDataAdapter data = new MySqlDataAdapter(cmd); conn.Open(); DataTable dt = new DataTable(); data.Fill(dt); gridView1.DataSource = dt; int retrievedValue = 0; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { if ((int)reader["order_status"] == 0) { retrievedValue = (int)reader.GetValue(0); GridView View2 = sender as GridView; e.Appearance.BackColor = Color.Green; e.Appearance.BackColor2 = Color.ForestGreen; } } }推荐答案
reader["order_status"]返回object,因为您已经告知它是一个已经整数,所以需要将其强制转换为int首先.
reader["order_status"] returns object, since you told it is an already integer, you need to cast it to int first.
您还需要使用 ==运算符,因为它是一个相等运算符. =运算符是赋值运算符.
You need to use == operator as well since it is a equality operator. = operator is an assignment operator.
if ((int)reader["order_status"] == 0)或者您可以使用 GetInt32方法及其基于从零开始的列号.假设它是查询返回的第一列,您可以像这样使用它;
Or you can use GetInt32 method with it's zero-based column number. Let's say it's the first column that your query returns, you can use it like;
if(reader.GetInt32(0) == 0)顺便说一句,如果您只想获得单个值,我强烈怀疑您可能想使用 ExecuteScalar 方法,因为它位于第一行的第一列.然后,您可以将查询构造为SELECT order_status FROM ...等.
By the way, if you wanna get only single value, I strongly suspect you may wanna use ExecuteScalar method since it get's the first column of the first row. Then you can structure your query as SELECT order_status FROM ... etc..
更多推荐
使用MySQL数据阅读器
发布评论