开发者

InvalidOperationException was unhandled

I receive no errors when i compile the program, however as soon as I click the save button I receive 'InvalidOperationException was unhandled'. cmd.ExecuteNonQuery(); Is then highlighted, ive spent a while on this and no luck. Hope you can help.

private void save_Click(object sender, EventArgs e)
{
    MySqlConnection con = new MySqlConnection("host=" ";user="";password=""; database="" ;");
    con.Open();

    MySqlCommand cmd = new MySqlCommand("INSERT INTO Staff (username, password, FirstName, SecondName, Phone, Email, Role, Phone 2, Fax)" + "values" + "("+username+","+password+","+Fname+","+Lname+","+Phone+","+email+","+role+","+Phone2+","+Fax+")");
    cmd.BeginExecuteNonQuery();
    cmd.ExecuteNonQuery();

    con.Close();            

    MessageBox.Show("Data Inserted");
    con.Close();开发者_运维知识库          
}


Assign the connection to your command before executing it:

cmd.Connection = con;

And remove the call to BeginExecuteNonQuery. It starts an async execution and directly after that you start a synchronous one. The way your code is structured, you wanted to use the synchronous way.


Define the connection for command by

cmd.Connection = con;

Moreover your query seems to be incorrect.

MySqlCommand cmd = new MySqlCommand("INSERT INTO Staff (username, password, FirstName, SecondName, Phone, Email, Role, Phone 2, Fax)"
            +"values" +"('"+username+"','"+password+"','"+Fname+"','"+Lname+"','"+Phone+"','"+email+"','"+role+"','"+Phone2+"','"+Fax+"')");

One more thing you have to do is rename the column name "Phone 2", do not use space in column name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜