【问题标题】:check if duplicate value is being added to mysql table检查是否将重复值添加到 mysql 表中
【发布时间】:2021-10-20 03:00:16
【问题描述】:

我正在创建一个程序来练习 MySQL,其中有一个名为 inventory 的表,用户添加到表中

item_code   item_name    price   quantity 
a000        a            100     100

我想这样做,如果用户输入 a000,那么他会收到 item_code 已经在表中的消息 有没有办法做到这一点

【问题讨论】:

    标签: python mysql database


    【解决方案1】:

    您可以在item_code 字段上指定唯一索引。

    CREATE UNIQUE INDEX item_code_unique
    ON inventory(item_code);
    

    然后您可以使用try-catch 块来捕获插入重复项的任何错误。

    try:
        cursor.execute("INSERT INTO ....")
    except MySQLdb.IntegrityError:
        print("Duplicate entry")
    

    另请参阅:How to avoid duplicate entries in a MySQL database without throwing an error

    Using MySQL UNIQUE Index To Prevent Duplicates

    【讨论】:

      【解决方案2】:

      试试这个:

      import sqlite3
      conn = sqlite3.connect("NameOfYourDatabase.db")
      cur = conn.cursor()
      cur.execute("""CREATE TABLE IF NOT EXISTS inventory (
                            item_code text UNIQUE,
                            item_name text,
                            price INT,
                            quantity INT
                            )"""
      try:
         #INSERT whatever you want into the db here 
      
      except sqlite3.IntegrityError:
         print("Item code already exists")
      

      您还可以将您的 item_code 设置为 PRIMARY KEY,因为 PRIMARY KEY 会自动设置为 UNIQUE

      记住:每张桌子只能有一个PRIMARY KEY

      如果您的表已经创建:

      ALTER TABLE inventory
         MODIFY item_code text NOT NULL UNIQUE;
      

      PRIMARY KEY:

      ALTER TABLE inventory
      ADD PRIMARY KEY (item_code);
      

      在本网站了解更多信息:

      https://www.w3schools.com/sql/sql_unique.asp

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-18
        • 1970-01-01
        • 2013-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-13
        • 2020-06-17
        相关资源
        最近更新 更多