我试图将值添加到数据库中,但是每次尝试添加某些内容时,都会收到错误消息“连接必须有效且打开”。

时间:2018-06-30 07:31:19

标签: c# mysql .net

这是我得到的错误:

enter image description here

使用以下代码:

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();
    }
}

2 个答案:

答案 0 :(得分:1)

您可能忘记了致电Open

MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();  // wallah 
myCommand.ExecuteNonQuery();
myConnection.Close();

还尽可能使用using语句

免责声明:这仅是出于演示目的,我不对您致残的人负责,否则会对代码造成伤害

答案 1 :(得分:-1)

我相信您的INSERT语句应该在您打开与数据库的连接之后以及关闭之前的