连接必须有效且开放

时间:2012-10-19 08:37:09

标签: c# mysql

我正在使用一种方法从数据库中获取项目列表。我已经使用连接将数据插入数据库并且工作正常,但是当在gridview中显示数据时会弹出一个异常。您可以在下面找到使用的方法,将数据绑定到gridview的代码和用于gridview的asp。希望你能帮忙。感谢

检索数据的方法

public List<Bet> getBets()
        {
            MySqlCommand cmd = Connection.CreateCommand();
            cmd = new MySqlCommand("SELECT * FROM bets ORDER BY date");

            try
            {
                if (this.Connection.State == ConnectionState.Closed)
                    this.Connection.Open();

                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); --> getting exception here
                List<Bet> bets = new List<Bet>();

                while (dr.Read())
                {
                    Bet myBet = new Bet();
                    myBet = FillBetfromRow(dr);
                    bets.Add(myBet);
                }
                return bets;
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
            finally
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();
            }
        }

将数据绑定到gridview

gvBets.DataSource = new BetManagement().getBets();
            gvBets.DataBind();

3 个答案:

答案 0 :(得分:0)

尝试使用“使用关键字”进行更改。数据阅读器关闭可能存在问题

 try
        {
            if (this.Connection.State == ConnectionState.Closed)
                this.Connection.Open();
            List<Bet> bets = new List<Bet>();
            using(MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)){


            while (dr.Read())
            {
                Bet myBet = new Bet();
                myBet = FillBetfromRow(dr);
                bets.Add(myBet);
            }
       }
            return bets;
        }

答案 1 :(得分:0)

在while循环之后关闭Datareader,就像dr.close()一样,并为你的命令分配连接con

答案 2 :(得分:0)

您未在Connection对象中设置Command

MySqlCommand cmd = Connection.CreateCommand();
cmd = new MySqlCommand("SELECT * FROM bets ORDER BY date");
cmd.Connection = this.Connection;