当数据库中已经存在相同的数据时,如何覆盖或跳过数据?



我正在从包含一些重复数据的文本文件中获取数据。我正试图将它们插入数据库而不复制。我在插入重复数据时遇到了麻烦。不应再次插入。数据不是静态值。

text_file = open(min_file, " ")#doc = text_file.readlines()对于text_file中的行:Field = line.split(";")打印(字段)

try:
connection = mysql.connector.connect(host='localhost',
database='testing',
user='root',
password='root')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)

mycursor = connection.cursor()
#before inserting
mycursor.execute("Select * from ftp")
myresult = mycursor.fetchall()
for i in myresult:
print(i)
sql ="Insert into ftp(a,b,c,d) 
select * from( Select VALUES(%s,%s,%s,%s) as temp 
where not exists 
(Select a from ftp where a = %s) LIMIT 1"

mycursor.execute(sql,field)
print(mycursor.rowcount, "record inserted.")
connection.commit()
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

一个选项是添加唯一约束,让DB验证唯一性,这将抛出异常,您可以捕获并跳过。

最新更新