python - 当数据库中已经存在相同的数据时,如何覆盖或跳过数据?
问题描述
我正在从包含一些重复数据的文本文件中获取数据。我正在尝试将它们插入数据库而不进行重复。我在插入重复数据时遇到了麻烦。它不应该再次插入。数据不是静态值。
text_file = open(min_file, "r") #doc = text_file.readlines() for line in text_file: field = line.split(";") print(field)
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")
解决方案
一种选择是添加唯一约束并让数据库验证唯一性,这将引发您可以捕获和跳过的异常。
推荐阅读
- javascript - 如何从公共谷歌日历中仅获取某些事件并将事件日期插入 js 倒计时
- sql - 插入中的行号
- java - 使用 NAMED 对象列表反序列化 JSON 响应
- c - 尝试在 ELF 二进制文件中执行注入代码时收到分段错误
- node.js - Nest.js 部署使用多个 lambda 函数
- android - ViewPAger2 中带有 GridLayoutManager 的 RecyclerView 在前 3 页中没有显示任何内容
- css - 反应 CSS 表单验证
- python - 不调用 mosquitto -d 就不会启动 Mosquitto
- amazon-web-services - Java SDK v2.x 中 KCL 的 dynamodb 流适配器
- php - 使用 PHP 清理 HTML 源代码