首页 > 解决方案 > 为什么语法错误(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")

 `

标签: pythonmysqlpymysqlexcept

解决方案


每个数据库实现(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()

推荐阅读