我正在創建一個程式來練習 MySQL,其中有一個名為清單的表,用戶添加到該表中
item_code item_name price quantity
a000 a 100 100
我想這樣做,如果用戶輸入 a000 然后他會收到一條訊息,表明 item_code 已經在表中,有沒有辦法做到這一點
uj5u.com熱心網友回復:
您可以在item_code欄位上指定 UNIQUE 索引。
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 索引防止重復
uj5u.com熱心網友回復:
嘗試這個:
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 a PRIMARY KEYas aPRIMARY 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326428.html
上一篇:如何輸出沒有空格的句子或短語?
下一篇:在理解中訪問字串的索引
