【问题标题】:Getting problem when trying to check if value already exist in sql table. Dont want dupesGetting problem when trying to check if value already exist in sql table. Dont want dupes
【发布时间】:2022-12-27 19:17:44
【问题描述】:

I'm right now learning more about C# and SQL connections and doing a challenge their I'm making a simple atm.

This atm will handle create account, check if its exist in database and if not then add to database, if it exist then close the program. Also it will handle rest of the parts an atm does once you have logged in to your card. With take outs and input.

This challenge are just for me to learn more of SQL and C#.

My issue: I'm trying to check if the value exist already in my SQL table but I'm not sure what I'm doing wrong.

Thanks in advance!

  bool checkifExist(int number) {
        bool itExist;
        string queryString;
        var cnn = new SqlConnection(connectionString);
        DataTable dt = new DataTable();
        try
        {
            cnn.Open();

            queryString = "select Count(*) from dbo.User_Card_Information where [CardNumbers] = @cardnumbers";
            SqlCommand check_cardnumber = new SqlCommand(queryString, cnn);
            check_cardnumber.Parameters.AddWithValue("@cardnumbers", cardnumber);
            int cardExist = (int)check_cardnumber.ExecuteScalar(); 
            if(check_cardnumber.ExecuteNonQuery() != cardnumber)
            {
             
                Console.WriteLine("Create completed!");
                cnn.Close();
                return itExist = false;

            }
            else
            {
                Console.WriteLine("This Card Number already exist!");
                itExist = true;
                cnn.Close();
                return itExist;

            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            cnn.Close();
        }
    }

【问题讨论】:

  • What is the exception if any? In general you should do this in the database not at the client. It's always possible that multiple clients trying to insert at the same time, so you have a race condition. So provide stored-procedures which do that.
  • "and if not then add to database" < this part seem to be missing from your code.
  • I have the add to database in other funktion, this one that I have problems with are just checking if the new value that I'm trying to add exist or not. If it exist then it will send the value true back and then the other funktion will work with that. Same if it dont exist. Its just the check if exist already part that I have issue with.

标签: c# sql .net


【解决方案1】:

If you want to avoid duplicates in a database, you can set a constraint on the column. The constraint UNIQUE makes sure that the value of that column only exists once.

More about constraints

In your code you execute the same query twice, which does not make sense:

            queryString = "select Count(*) from dbo.User_Card_Information where 
            [CardNumbers] = @cardnumbers";
            SqlCommand check_cardnumber = new SqlCommand(queryString, cnn);
            check_cardnumber.Parameters.AddWithValue("@cardnumbers", 
            cardnumber);
        >   int cardExist = (int) check_cardnumber.ExecuteScalar();
        >   if(check_cardnumber.ExecuteNonQuery() != cardnumber)
            {
             
                Console.WriteLine("Create completed!");
                cnn.Close();
                return itExist = false;

            }

Furthermore you are using SqlCommand.ExecuteNonQuery() which returns the rows affected, which is not what you want.

You should compare the result of (int)check_cardnumber.ExecuteScalar() with the given card_number.

【讨论】:

    【解决方案2】:

    If the intention is to check if the data is present in the table or not, you can query only the top row instead of all, in which case you would not get exceptions for multiple or duplicate rows.

    【讨论】:

      【解决方案3】:

      Hi i think you need something like this

              object result = cmd.ExecuteScalar(); // ExecuteScalar fails on null
              if (result.GetType() != typeof(DBNull))
              {
                  test = (int?)result;
              }
      

      【讨论】:

        【解决方案4】:
        public static void InsertRecord()
                    {
                        SqlConnection connection= new SqlConnection(CONNECTION_STRING);
                        try
                        {
                            connection.Open();
                            int x;
                            Console.WriteLine("Enter username:");
                            string user = Console.ReadLine();
                            string query = "insert into userTable values (@val)";
                            using(SqlCommand command = new SqlCommand(query, connection))
                            {
                                command.Parameters.AddWithValue("@val", user);
                                x=command.ExecuteNonQuery();
                            }
                            if(x==0)
                            {
                                Console.WriteLine("user already exists in Database.");
                            }
                            Console.WriteLine("user inserted successfully.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        finally 
                        {
                            connection.Close();
                        }
        
                    }
        

        【讨论】:

          猜你喜欢
          • 2022-12-01
          • 2022-12-19
          • 2021-03-09
          • 1970-01-01
          • 2022-12-16
          • 1970-01-01
          • 2022-12-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多