bha*_*ral 13 python mysql-python
我有这个代码:
cursor = conn.cursor()
cursor.execute(("insert into new_files (videos_id, filename, "
"is_processing) values (%s,%s,1)"), (id, filename))
logging.warn("%d", cursor.rowcount)
if (cursor.rowcount == 1):
logging.info("inserted values %d, %s", id, filename)
else:
logging.warn("failed to insert values %d, %s", id, filename)
cursor.close()
Run Code Online (Sandbox Code Playgroud)
有趣的是,cursor.rowcount是总是一个,即使我更新了我的数据库,以使videos_id一个独特的密钥.也就是说,插入失败,因为在我的测试videos_id中会出现同样的情况(当我检查数据库时,没有插入任何内容).但无论出于何种原因,rowcount它总是1 - 即使logging.warn我已经吐了rowcount1.
所以,问题是:如果插入正常,
我可以使用rowcount吗?如果是这样,我(大概)做错了什么?否则,我如何检查插入是否正常?
new*_*ver 32
修改后您的代码不会提交(您的修改将被回滚).那就是你应该在以下后面添加以下行cursor.execute:
conn.commit()
Run Code Online (Sandbox Code Playgroud)
插入失败将抛出MySQLdb.IntegrityError,因此您应该准备好捕获它.
因此,您的代码应该类似于:
sql_insert = """insert into new_files (videos_id, filename, is_processing)
values (%s,%s,1)"""
cursor = conn.cursor()
try:
affected_count = cursor.execute(sql_insert, (id, filename))
conn.commit()
logging.warn("%d", affected_count)
logging.info("inserted values %d, %s", id, filename)
except MySQLdb.IntegrityError:
logging.warn("failed to insert values %d, %s", id, filename)
finally:
cursor.close()
Run Code Online (Sandbox Code Playgroud)