0

How do I check my database so that when registering, it does not allow the customer to register as the username is being used?

CustomerRegisteration.cs

string selStr = "Insert Into CustomerTbl(customer_username,customer_name,customer_age,customer_address,customer_password,customer_security_question,customer_security_answer)"
                    + "Values('" + usernameTextBox.Text + "'" + "," + "'" + nameTextBox.Text + "'" + "," + "'" + ageTextBox.Text + "'" + "," + "'" + addressTextBox.Text + "'" + "," 
                    + "'" + passwordTextBox.Text + "'" + "," + "'" + questionComboBox.Text + "'" + "," + "'" + answerTextBox.Text + "')";

                int i = dbObj.ExecuteNonQuery(selStr);

My Database

class DataBase
    {
        string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\OOPG\Banking Mini Project Raynard\Banking Mini Project Raynard\Database1.mdf;Integrated Security = True";
        SqlConnection connObj;
        SqlCommand comdObj;
        SqlDataReader dR;

        public DataBase()
        {
            connObj = new SqlConnection(connStr);
            connObj.Open();
        }
        public SqlDataReader ExecuteReader(string selStr)
        {
            comdObj = new SqlCommand(selStr, connObj);
            dR = comdObj.ExecuteReader();
            return dR;
        }
        public int ExecuteNonQuery(string sqlStr)
        {
            comdObj = new SqlCommand(sqlStr, connObj);
            return comdObj.ExecuteNonQuery();
        }

    }
Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
  • 5
    Do a `select` before the insert and check? Also **do not** build sql queries like that. *Always* parameterize your queries. Unless you want a [Little Bobby Tables](https://xkcd.com/327) incident... – Broots Waymb Jan 26 '21 at 13:45
  • 2
    Put an `UNIQUE` constraint, do the `INSERT` normally and catch the duplicate exception. – Alejandro Jan 26 '21 at 13:48
  • 1
    And don't waste your time building a database class. You can rest assured that you will make mistakes (and yes you have already made errors in that class) and there are other better approaches like using an ORM library – Steve Jan 26 '21 at 13:55
  • **See [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice)** – Charlieface Jan 26 '21 at 16:11
  • So what is the best way to connect a sql database into my visual studio 2019 project? – millionclones Jan 27 '21 at 00:03

0 Answers0