0

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.

2
  • 1
    I advise against having users input their own primary key value. The database can and normally should handle that for you. Commented Jul 6, 2022 at 11:56
  • please use parameterised queries - building SQL queries by concatenation etc. is a recipe for disaster. not only is it a source for many hard to debug syntax errors, it's also a wide, open gate for SQL Injection attacks. Commented Jul 6, 2022 at 11:59

1 Answer 1

1

Change cmdString:

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

Sign up to request clarification or add additional context in comments.

3 Comments

Ok so I ended up with: "IF EXISTS (SELECT * FROM main WHERE cust_ID =" + id + " RETURN -1 ELSE INSERT INTO main VALUES ('"+ id + "','" + name + "','" + total_items + "'));"; the thing is how do I make it so that the error messagebox to displays if the Id already exists?
Does RETURN work/do anything in MySql outside of a procedure or function?
@PythonicUser if sql returns -1 display that user exists. executenonquery catches return values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.