当我将我的asp.net Web表单应用程序连接到localhost上的mysql数据库时,我是C#的新程序员
我收到此错误:
MySql.Data.dll中出现'System.InvalidOperationException'类型的异常,但未在用户代码中处理
为什么我需要帮助
我在堆栈上发现了一些东西,但我不知道如何使用他们的特定解决方案。
关于我的代码
在我的代码中,我试图连接到mysql并调用简单的sql命令 有我的代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft;
using Newtonsoft.Json;
using System.Diagnostics;
using MySql.Data;
using MySql;
using MySql.Data.MySqlClient;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
MySqlConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckMysqlConnection();
}
UploadToMysqlDatabase();
}
private void CheckMysqlConnection() {
//connection string
string connectionString = @"Server=localhost;Database=ev3;Uid=root;Pwd=;";
using (connection = new MySqlConnection(connectionString))
{
if(connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
Response.Write("Mysql Connection Succesful");
}
}
}
private void UploadToMysqlDatabase() {
//Debug.WriteLine(objekt.portId);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM robot",connection);
cmd.ExecuteNonQuery(); ***// there is error***
//connection.Close();
}
}
错误明细
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Connection must be valid and open.
Source=MySql.Data
StackTrace:
v MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
v MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
v MySql.Data.MySqlClient.MySqlCommand.CheckState()
v MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
v MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
v WebApplication2.WebForm1.UploadToMysqlDatabase() v C:\Users\Jan\Dropbox\infs1\insys2\WebApplication2\WebApplication2\WebForm1.aspx.cs:řádek 78
v WebApplication2.WebForm1.Page_Load(Object sender, EventArgs e) v C:\Users\Jan\Dropbox\infs1\insys2\WebApplication2\WebApplication2\WebForm1.aspx.cs:řádek 45
v System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
v System.Web.UI.Control.OnLoad(EventArgs e)
v System.Web.UI.Control.LoadRecursive()
v System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
答案 0 :(得分:0)
当connection.Open()
包含在using (connection = new MySqlConnection(connectionString))
语句中时,它将在完成后自动处理(不再打开以供将来使用)。您试图以完全独立的方法使用已处理的连接。您需要做的是调用private void UploadToMysqlDatabase()
方法并将连接作为参数传递(即。private void UploadToMysqlDatabase(string conn)
,或者在connection.Open()
方法中创建新的UploadToMysqlDatabase()
。