我正在尝试在数据库中添加替换数据,但它总是创建新数据而不是替换现有数据。我该怎么办?
# Import module
import sqlite3
#data
name = "ravi"
std = "12"
sec = "b"
conn = sqlite3.connect('sample.db')
cursor = conn.cursor()
# Creating table
table ="""CREATE TABLE IF NOT EXISTS STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),
SECTION VARCHAR(255));"""
cursor.execute(table)
# Queries to INSERT records.
cursor.execute('''INSERT OR REPLACE INTO STUDENT VALUES (?,?,?)''',(name,std,sec))
cursor.execute('''INSERT OR REPLACE INTO STUDENT VALUES ('Shyam', '8th', 'B')''')
cursor.execute('''INSERT OR REPLACE INTO STUDENT VALUES ('Baburao', '9th', 'C')''')
# Display data inserted
print("Data Inserted in the table: ")
data=cursor.execute('''SELECT * FROM STUDENT''')
for row in data:
print(row)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
创建表后,需要创建3个字段的唯一索引
name
class
section
如果数据库中已经有重复的字段,请先删除重复的行。
unique_index_query = """CREATE UNIQUE INDEX IF NOT EXISTS idx_name_class_section ON STUDENT(NAME, CLASS, SECTION);"""
cursor.execute(unique_index_query)
您可以在这里参考更多