检查是否重复的值被添加到mysql表



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

item_code   item_name    price   quantity 
a000        a            100     100

我想这样做,如果用户输入a000,那么他得到item_code已经在表中的消息有办法吗?

可以指定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")

参见:如何避免MySQL数据库中的重复条目而不抛出错误

使用MySQL UNIQUE索引防止重复

试试这个:

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;

WithPRIMARY KEY:

ALTER TABLE inventory
ADD PRIMARY KEY (item_code);

在此网站了解更多信息:

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

最新更新