Reputation: 120
I have this C# gui application that take user inputs, id
name
total_items
the inputs value will be inserted into MySQL database on column cust_ID
cust_name
cust_total_items
void Button2Click(object sender, EventArgs e)
{
try {
con = new MySqlConnection("server=localhost;database=csharp_database;username=root;password=nfreal-yt10;");
con.Open();
MySqlCommand sql_cmd = null;
int id = Convert.ToInt32(textBox1.Text);
String name = textBox2.Text;
int total_items = Convert.ToInt32(textBox3.Text);
String cmdString = "INSERT INTO main VALUES ('"+ id + "','" + name + "','" + total_items + "');";
sql_cmd = new MySqlCommand(cmdString,con);
sql_cmd.ExecuteNonQuery();
if(id == cust_ID) {
MessageBox.Show("ID Already exists");
}
if(sql_cmd != null) {
MessageBox.Show("Inserted Successfully");
}
con.Close();
} catch (Exception ef) {
Console.WriteLine(ef);
}
}
I want to make it that when the new user entered an ID that is equivalent to the already existing ID from cust_ID column value to not insert the input ID into MySQL database and return a messagebox that display "ID Already exists". How do I implement this?, I have done couple of googling yet no solution.
Upvotes: 0
Views: 90
Reputation: 59
Change cmdString:
"IF EXISTS (SELECT * FROM main WHERE id =" + id + " RETURN -1 ELSE INSERT ..."
Upvotes: 1