每个数据库实现(MySQL、sqlite、...)都可能引发它们的特定异常。因此,您可以根据特定的 DB,然后根据特定类型(例如 SyntaxError)捕获错误,而不是捕获一般异常。我建议在您的 SQL 语句上引发语法错误,然后查看是什么类型(例如错误代码或异常类型)然后捕获它。
例如,MySQL 连接器引发error numbers:
import mysql.connector as cn
try:
#...
except cn.Error as err:
print("Something went wrong: {}".format(err))
if err.errno == errorcode.ER_BAD_TABLE_ERROR: #
这里有一些MySQL Error Code Ranges
如果您使用的是 MySQLdb:
import MySQLdb
try:
#...
cursor.execute(sql)
res = cursor.fetchone()
# ...
except MySQLdb.Error, e:
print "MySQLdb.Error: {}".format(e.args)
根据您的架构(列类型)和输入变量的类型,您可以使用:
sql="Update cours set nomC='%s' where num_cours=%s" # Added quotes on the first replacement
除了你问的,我认为命令顺序是颠倒的。
sql="Update cours set nomC=%s where num_cours=%s"
cursor.execute(sql,(nvcours,num_cours)) # First
result=cursor.fetchone() # Second
print("Operation Done.")
https://www.tutorialspoint.com/python/python_database_access.htm
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()