开发者

C# MySQL Problems

开发者 https://www.devze.com 2023-03-03 22:50 出处:网络
The following code is throwing an error: ExecuteReader requires an open and available Connection. The connection\'s current state is closed.

The following code is throwing an error: ExecuteReader requires an open and available Connection. The connection's current state is closed.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {        
    public String conString =
      "DRIVER={MySQL ODBC 5.1 Driver};" +
      "SERVER=localhost;" +
      "DATABASE=habcms;" +
      "USER=root;" +
      "PASSWORD=password;";

    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {                
      OdbcConnection db = new OdbcConnection();
      String quer = "SELECT `password` FROM `users` WHERE `username` = 'Joshwaa'";
      OdbcCommand cmd = new OdbcCommand(quer, db);
      开发者_开发知识库OdbcDataReader dString = cmd.ExecuteReader();

      string theValue = dString.GetString(1);
    }
  }
}


You forgot to .Open() the connection.


You must open the connection using Open():

private void button1_Click(object sender, EventArgs e)
{
        OdbcConnection db = new OdbcConnection();
        String quer = "SELECT `password` FROM `users` WHERE `username` = 'Joshwaa'";
        OdbcCommand cmd = new OdbcCommand(quer, db);
        db.Open();
        OdbcDataReader dString = cmd.ExecuteReader();
        string theValue = dString.GetString(1);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消