Reputation: 3
I have a problem in my application that I am developing.
I Insert 4 Data FieldsLets call them ("Age"
, "Gender"
, "Name"
, "Tel"
) in to a MySQL database. 99% of the time it will work 100% then once in a while I will get something odd.
Row 1 will have the Age , Gender, "Null" , "Null" and row 2 Will have "Null" , "Null" , Name , Tel so basically it will insert one line of data into 2 rows.
Below is the sample of the code:
String constring = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
string Query = "insert into db.Table (Name , Surname , ID , Tel)
values('" + this.textBox1.Text + "' , '" + this.textBox2.Text + "' ,
'" + this.textBox6.Text + "' , '" + this.textBox4.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
conDataBase.Open();
try
{
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Cleint Details has been added to system");
}
If anyone can think of a reason for this please help. I did check the environment (network connection etc.) but those are fine.
Upvotes: 0
Views: 106
Reputation: 94
I think Reece's answer is going to solve your problem, but I also recommend ditching the ExecuteReader()
and while{}
loop. Instead just use cmdDataBase.ExecuteNonQuery();
to fire the insert.
Upvotes: 0
Reputation: 2964
It is possible there are values in the text box that are affecting the insert statement. It would be better if you used parameterised statements. E.g.:
string Query = "insert into db.Table (Name , Surname , ID , Tel) values(@param1, @param2 , @param3 , @param4);";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
//Add paramter values
cmdDataBase.Parameters.AddWithValue("@param1", this.textBox1.Text);
cmdDataBase.Parameters.AddWithValue("@param2", this.textBox2.Text);
cmdDataBase.Parameters.AddWithValue("@param3", this.textBox6.Text);
cmdDataBase.Parameters.AddWithValue("@param4", this.textBox4.Text);
Upvotes: 2