C# I';我试图向数据库中添加值,但每次尝试添加某些内容时都会出现错误';连接必须有效且开放;
这就是我得到的错误: 使用此代码:C# I';我试图向数据库中添加值,但每次尝试添加某些内容时都会出现错误';连接必须有效且开放;,c#,mysql,.net,C#,Mysql,.net,这就是我得到的错误: 使用此代码: private void button1_Click_1(object sender, EventArgs e) { if (txtID.Text == "" || txtName.Text == "" || txtMobileNo.Text == "") { MessageBox.Show("Please Enter all of your detail.", "Stop", MessageBoxButtons.OK, Me
private void button1_Click_1(object sender, EventArgs e)
{
if (txtID.Text == "" || txtName.Text == "" || txtMobileNo.Text == "")
{
MessageBox.Show("Please Enter all of your detail.", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
else
{
string query = "INSERT INTO tablemm (id,Name,MobileNo) VALUES ('" + txtID.Text + "','" + txtName.Text + "','" + txtMobileNo.Text + "')";
OpenConnection();
MySqlCommand ObjCommand = new MySqlCommand(query, ObjConnection);
ObjCommand.ExecuteNonQuery();
this.CloseConnection();
}
}
您可能忘记调用
Open
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open(); // wallah
myCommand.ExecuteNonQuery();
myConnection.Close();
在可能的情况下,也可以使用语句
免责声明:此声明仅用于演示目的,我对您使用此代码致残或伤害的人不承担任何责任我相信您的插入声明应该在您打开与数据库的连接之后,在您关闭它之前进行。您怎么知道,他/她没有在OpenConnection()中调用Open
代码>方法?是的,事实上他是对的,但现在另一个问题是PopupMySql.Data.MySqlClient.MySqlException:“主机localhost不支持SSL连接”。@imzia99这基本上是另一个问题,尽管这可能有助于提醒您!发布完整的代码!ObjConnection和OpenConnection()方法代码也不链接图片,它让我们点击,我们讨厌点击//全局变量private MySqlConnection ObjConnection;私有字符串服务器、数据库、uid、密码//初始化连接私有void InitializeConnection(){server=“localhost”;database=“table”;uid=“root”;password=“;string connectionString=“server=“+server+”;“+”database=“+database+”;“+”uid=“+uid+”;“+”password=“+password+”;”;ObjConnection=new MySqlConnection(connectionString);}private bool OpenConnection(){try{ObjConnection.Open();返回true;}catch(MySqlException ex){switch(ex.Number){case 0:MessageBox.Show(“无法连接到服务器”);break;case 1045:MessageBox.Show(“无效用户名/密码”);break;}返回false;}你是认真的吗?是的,是在开放连接之后,实际上是在最后