简体   繁体   中英

Determine if user input is equivalent to value from MySQL database column from C# Input

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.

Change cmdString:

"IF EXISTS (SELECT * FROM main WHERE id =" + id + " RETURN -1 ELSE INSERT ..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM