C# MySQL Problems

本文关键字:Problems MySQL | 更新日期: 2023-09-27 17:55:41

以下代码引发错误: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);
    }
  }
}

C# MySQL Problems

您忘了.Open()连接。

您必须使用 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);
}