Harikeinas Harikeinas - 5 months ago 8
MySQL Question

Can't insert data to mysql, fatal error encountered

To be honest i just got interested in programming and this is my first project and i am stucked. So i created dinamical textboxes and i want to save information to the database, but fatal error pops up every time. I know that connection is correct. i know the problem is with dinamical textboxes, searched threw internet, didn't found solution, sorry for bad english, hope you can help me.

private void button2_Click(object sender, EventArgs e)
{
TextBox textbox1 = new TextBox();
textbox1.Size = new Size(75,23);
textbox1.Text = "Pav.";
textbox1.Location = new Point(0, 0);
panel1.Controls.Add(textbox1);
string name = textbox1.Text;

TextBox textbox2 = new TextBox();
textbox2.Size = new Size(75, 23);
textbox2.Text = "0.5";
textbox2.Location = new Point(80, 0);
panel1.Controls.Add(textbox2);
float sum = float.Parse(textbox2.Text);

ComboBox comboBox4 = new ComboBox();
comboBox4.Size = new Size(75, 23);
comboBox4.Text = "-Type-";
comboBox4.Items.Add("Salary");
comboBox4.Location = new Point(170, 0);
comboBox4.Items.Add("Other");
comboBox4.Name = "comboBox4";
panel1.Controls.Add(comboBox4);



Button btn = new Button();
btn.Text = "Save";
btn.Location = new Point(250, 0);
btn.Click += delegate
{
if (comboBox4.SelectedItem.ToString() == "Salary")
{
string myConnection = "datasource=localhost; port=3306; username=root; password=root";
string insert = "insert into budget.incomes (Name, sum) values (@Name, @sum);";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(insert, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Saved");
this.Close();
while (myReader.Read())
{ }

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Answer

You don't need the DataReader and you need to use parameters.

string myConnection = "datasource=localhost; port=3306; username=root; password=root";
string insert = "insert into budget.incomes (Name, sum) values (@Name, @sum);";

using (var conDataBase = new MySqlConnection(myConnection))
using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
{       
    cmdDataBase.Parameters.AddWithValue("@Name", name);
    cmdDataBase.Parameters.AddWithValue("@Sum", sum);
    conDataBase.Open();
    cmdDataBase.ExecuteNonQuery();
    MessageBox.Show("Saved");       
}
this.Close();