Reputation: 209
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();
}
Upvotes: 0
Views: 8850
Reputation: 2796
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.
Upvotes: 1
Reputation: 174299
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.
Upvotes: 7