【问题标题】:why do Syntax error (python) doesn't work?为什么语法错误(python)不起作用?
【发布时间】:2020-05-22 18:02:10
【问题描述】:

我想打印一条消息,以防用户在编写代码时出错但它不起作用我还尝试添加 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")

 `

【问题讨论】:

  • 请编辑您的问题以包含完整的错误回溯。谢谢。

标签: python mysql pymysql except


【解决方案1】:

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

【讨论】:

  • 谢谢 Omr 先生,您是对的。我没有注意到。但是我的 Try 有问题,除非它在我需要时不起作用..
  • 错误信息是什么?您使用的是什么类型的数据库?您正在使用什么数据库包装库(即导入什么)?
  • PyMySQL// MySQL//Inno DB //Python 3.7
猜你喜欢
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
相关资源
最近更新 更多