从 mysql 服务器错误 [] 中提取文本

Extracting text from mysql server error []

如果我在 pymysql 中发出无效的 sql 语句,我会得到如下异常:

c.cursor.execute('select * fromd')
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fromd' at line 1")

我如何在响应中得到文本错误?

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fromd' at line 1"

目前我在做的是:

try:
    c.cursor.execute('asdf')
except Exception as e:
    print (e)

但这给了我一个"string tuple"。这个模块中有没有办法只获取错误消息本身?

您可以使用 e.args:

try:
    self.cursor.execute(query)
except pymysql.err.ProgrammingError as e:
    error_msg = e.args[1]
    raise ConnectionError(error_msg)

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'asdf' at line 1

您应该捕获特定错误:

import pymysql  
try: 
    raise pymysql.err.ProgrammingError(1064,"Bla")
except pymysql.err.ProgrammingError as prgError:
    if len(prgError.args)>1:
        print(prgError.args[1])  # might be not code + message but code only
    else:
        print(e)
except Exception as e:
    print (e)

输出:

Bla