Windows应用程序中

Windows应用程序中

我收到错误消息:


  类型为“ System.InvalidOperationException”的未处理异常
  发生在MySql.Data.CF.dll中


在我的Windows应用程序中。

下面是我的代码。

In app.config:

inside connectionStrings tag

add name="ConnectionString"
connectionString="server=localhost;database=my_db;user=root;port=3306;
password=mypwd;

In LoginForms.cs

using System.Configuration;
using MySql.Data.MySqlClient;

namespace MySoftware
{
public partial class Login : Form
{
MySqlConnection conn;
public static int valid = 0;
public Login()
{
InitializeComponent();
}

private void btnLogin_Click(object sender, EventArgs e)
{
var connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new MySqlConnection(connectionString);
conn.open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Verify_Login";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@uname", textBox1.Text);
cmd.Parameters["@uname"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("@pwd", textBox2.Text);
cmd.Parameters["@pwd"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("@result", MySqlDbType.Int32);
cmd.Parameters["@result"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery(); // At this line the error is thrown
int valid = (int)(cmd.Parameters["@result"].Value);
}
}
}

Verify_Login is a stored procedure which is created in MySQL as below.

CREATE PROCEDURE `Verify_Login`(in uname varchar(20),in pwd varchar(20),out
result bool)
BEGIN
select count(*) into result from Login where uname=uname and password=pwd;
END

Could anyone please help me with this?

最佳答案

您的代码失败,因为试图执行命令,并且此命令未绑定到打开的连接。您有很多方法可以绑定连接

MySqlCommand cmd = conn.CreateCommand();


要么

MySqlCommand cmd = new MySqlCommand(sqlText, conn);


要么

MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;


当然,仍然建议使用适合您的环境的连接器。

您的代码重构了一点

private void btnLogin_Click(object sender, EventArgs e)
{
     var connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
     using(MySqlConnection conn = new MySqlConnection(connectionString))
     using(MySqlCommand cmd = new conn.CreateCommand())
     {
          conn.open();
          cmd.CommandText = "Verify_Login";
          cmd.CommandType = CommandType.StoredProcedure;
          .....
          cmd.ExecuteNonQuery();
          int valid = (int)(cmd.Parameters["@result"].Value);
     }
}

09-06 00:18