为什么语法错误(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()

最新更新