How to add a record if the result of a SQL query is empty
I would like to check if some records exist in MySQL database and if they are missing I want to add some alternative information. I tried to use the following code but made a mistake. I am a beginner in c# and not sure how to do that. Please could you tell me what the problem is:
private void button1_Click(object sender, EventArgs e)
for (int has = 1; has <= 10; has++)
for (int ted = 1; ted <= 15; ted++)
for (int cin = 1; cin <= 20; cin++)
for (int yas = 1; yas <= 100; yas++)
String testsql = "Select * from v2007 where HASTALIK_GRUBU='" + has + "' and TEDAVI_ILI='" + ted + "' and CINSIYET='" + cin + "' and YAS='" + yas + "'";
MySqlCommand testcommand = new MySqlCommand();
testcommand.CommandText = testsql;
MySqlDataAdapter adapter2 = new MySqlDataAdapter();
adapter2.SelectCommand = testcommand;
DataTable dataset = new DataTable();
if (dataset.Rows.Count == 0)
String sql2 = "Insert into v2007(HASTALIK_GRUBU,TEDAVI_ILI,CINSIYET,YAS,AYAKTA,YATARAK) values('" + has + "','" + ted + "','" + cin + "','" + yas + "','0','0')";
MySqlCommand command2 = new MySqlCommand();
command2.CommandText = sql2;
label2.Text = "İşlem bitti";
Re: How to add a record if the result of a SQL query is empty
We shouldn't guess what's wrong with your code... provide some information about the error. Like... what's the Line number?
Also, you're attempting to connect to the database 15*20*100 times. Why not connecting outside the for loops?
I'd also consider to use a SELECT COUNT query, instead of selecting all the data, since all you really need is to check weather or not the Rows.Count is 0.
Alternatively you could select all the relevant data in one query and look for matches from the records placed in the Dataset.