-1

This is the error I'm getting:

enter image description here

with this code:

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();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
efaisalzia
  • 35
  • 8
  • 3
    [SQL-Injection](https://en.wikipedia.org/wiki/SQL_injection) Alert! – Salah Akbari Jun 30 '18 at 07:37
  • post the full code! ObjConnection and OpenConnection() method code – Prashant Pimpale Jun 30 '18 at 07:37
  • Also don't link pictures, it makes us click and we hate clicking – TheGeneral Jun 30 '18 at 07:41
  • //Global variable private MySqlConnection ObjConnection; private string server, database, uid, password; //intialize connection private void InitializeConnection() { server = "localhost"; database = "table"; uid = "root"; password = ""; string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; ObjConnection = new MySqlConnection(connectionString); } – efaisalzia Jun 30 '18 at 08:25
  • private bool OpenConnection() { try { ObjConnection.Open(); return true; } catch (MySqlException ex) { switch (ex.Number) { case 0: MessageBox.Show("Can not connect to server"); break; case 1045: MessageBox.Show("Invalid User name/Password"); break; } return false; } } – efaisalzia Jun 30 '18 at 08:28

2 Answers2

1

You have probably forgotten to call Open

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

Also use a using statement where possible,

Disclaimer: This is only for demonstration purposes and I can't be held responsible for the people you maim and otherwise hurt with this code

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
-1

I believe that your INSERT statement should be after you open your connection with the database and right before you close it.

jam
  • 1
  • 2