0

I've tried so hard to insert data on MySql server using this code :

private void button1_Click(object sender, EventArgs e)
{
    string con = "datasource=localhost;database=test;port=3307;username=root;password=root";
    MySqlConnection sq = new MySqlConnection(con);
    sq.Open();

    try
    {
        MySqlCommand com1 = new MySqlCommand("Insert into customerinfo(ID) values('" + textBox1.Text + "')", sq);
        com1.ExecuteNonQuery();
        //sq.Open();
    }
    catch (Exception ex)
    {
        MessageBox.Show("please, enter an ID with at most 3 characters !");
    }

    try
    {
        MySqlCommand com2 = new MySqlCommand("Insert into customerinfo(OwnerName) values('" + textBox6.Text + "')", sq);
        com2.ExecuteNonQuery();
        //sq.Open();
    }
    catch (Exception ex)
    {
        MessageBox.Show("please, enter a name with at most 30 characters !");
    }
}

The first try brackets are being excuted well, but for the second try, it throws an exeption! Please help me to know why is this happen?

JumpingJezza
  • 5,498
  • 11
  • 67
  • 106

1 Answers1

1

90% sure that your 'ID' field is required, so you cannot sent just the id... BTW, it seems you're inserting 2 rows, instead a single row with the two values... You may be trying to do:

 MySqlCommand com1 = new MySqlCommand("Insert into customerinfo(ID, OwnerName) values('" + textBox1.Text + "', '" + textBox6.Text + "')", sq);

Some extra tips here:

  • Open your connection within a using statement, so you ensure the connection memory disposal is handled and closed correctly.
  • Agreed that adding a dynamic query may result on your application being exposed to SQL injection (a whole topic that you may want to research about). So, just be sure you add a lot of validations on both client side and server side, have a stored procedure, or change this insert to be ORMified.

Hope this helps

David Espino
  • 2,177
  • 14
  • 21