python - 为什么语法错误(python)不起作用?
问题描述
我想打印一条消息,以防用户在编写代码时出错但它不起作用我还尝试添加 NameError 异常,它只有在我引发异常时才有效。谢谢你的帮助。
`
def cncours(nvcours,num_cours):
try :
sql="Update cours set nomC=%s where num_cours=%s"
result=cursor.fetchone()
cursor.execute(sql,(nvcours,num_cours))
print("Operation Done.")
except TypeError:
print("Plz put the name between quotes")
`
解决方案
每个数据库实现(MySQL、sqlite、...)都可能引发它们的特定异常。因此,您可以根据特定的数据库,然后根据特定的类型(例如 SyntaxError)来捕获错误,而不是捕获一般异常。我建议在您的 SQL 语句上引发语法错误,然后查看是什么类型(例如错误代码或异常类型)然后捕获它。
例如,MySQL 连接器会引发错误编号:
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 错误代码范围
如果您使用的是 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()
推荐阅读
- image-processing - 检测旋转的车辆图像
- ios - 条件绑定的初始化程序必须具有 Optional 类型,而不是 '[AnyHashable : Any]'
- android - 使用自定义 AutoML 模型进行 TensorFlow Lite 对象检测
- node.js - 无法使用 React 在电子应用程序上运行 NodeJS
- python - 使用嵌套结构按列连接 NumPy 数组
- scala.js - 将 Scala.js 类实例传递给将调用函数调用方法的 JavaScript
- ajax - 如何在弹出窗口中显示成功消息?
- amazon-web-services - AWS CloudWatch 事件未触发
- python-3.x - 如何为堆叠条形图中的每个图例标签设置唯一颜色
- scala - Scala:如何传递字符串变量来访问对象值?