使用MySQL数据阅读器 [英] Using MySQL Data Reader

查看:92
本文介绍了使用MySQL数据阅读器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉使用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)

或者您可以使用

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)

顺便说一句,如果您只想获得单个值,我强烈怀疑您可能想使用

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数据阅读器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆