繁体   English   中英

连接必须有效并打开SQL

[英]Connection must be valid and open SQL

出现问题了。 我检查了与数据库的连接-一切正常。 但是,当我尝试检查数据库中的行时,就会弹出错误:

System.InvalidOperationException:“连接必须有效且打开。” C#

我怎样才能解决这个问题?

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MySqlConnection conn = GetDBConnection();
            conn.Open();
            MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM 'rcc_base' WHERE login='" + this.textBox1.Text + "', pass='" + this.textBox2.Text + "' ;");
            MySqlDataReader myReader;
            MessageBox.Show("Connection...");
            myReader = selectCommand.ExecuteReader();
            int count = 0;
            while (myReader.Read())
            {
                count = count + 1;
            }

            if (count == 1)
            {
                MessageBox.Show("All nice");
            }
            else
            {
                MessageBox.Show("Login failed");
            }

            conn.Close();
        }
        catch (Exception)
        {
            MessageBox.Show("Error");
        }
    }

在您的MySqlCommand您没有使用MySqlConnection :(。

 MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM rcc_base WHERE 'login' ='" + this.textBox1.Text + "' AND 'pass' ='" + this.textBox2.Text + "' ;",conn);

同样,创建一个MySqlConnection的新实例,如:

  MySqlConnection conn = new MySqlConnection;
  conn = GetDBConnection();

还有一些建议:您的代码不好,不要直接给SqlCommand rahter传递参数中的列提供@@这样的@abc ,这也会阻止sql-injections.Sample:

  MySqlCommand selectCommand = new MySqlCommand("SELECT COUNT(*) FROM rcc_base WHERE login=@username AND pass=@password;",conn);

  selectCommand.Parameters.Add("@username",MySqlDbType.VarChar).Value = textBox1.Text;
  selectCommand.Parameters.Add("@password",MySqlDbType.VarChar).Value = textBox2.Text;

 ///Now to check if data exists in the database or not

 int count = Convert.ToInt32(selectCommand.ExecuteScalar());

 if(count > 0)
  {
   ///data exists-login successful

  }
   else

  {
  ///data doesn't exists , login failed
   }

另外,您应该在表单加载时打开连接,以便可以在整个类/表单中访问数据库,这是一种更好的方法:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM