首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3.7.5 Mariadb 10.4.11查询绑定导致异常

问Python3.7.5 Mariadb 10.4.11查询绑定导致异常
EN

Stack Overflow用户
提问于 2020-04-10 23:17:23
回答 1查看 46关注 0票数 0

在这个精心设计的例子中,我尝试选择“Fred”硬编码,然后使用绑定变量。

选得很好。绑定变量示例在异常情况下失败。

代码语言:javascript
复制
import sys
import string
import mysql.connector

def sanity_test():
    try:
        print("connecting")
        connection = mysql.connector.connect(user='root', password='root',
                                             host='127.0.0.1', database="MyJournal")
        print("test1")
        cursor1 = connection.cursor()
        cursor1.execute("select 'Fred'")
        records = cursor1.fetchall()
        print("There are " + str(cursor1.rowcount) + " rows in the first result set")

        print("test2")
        cursor2 = connection.cursor()
        name = "Fred";
        cursor2.execute("select %s", name)
        records2 = cursor2.fetchall()
        print("There are " + str(cursor2.rowcount) + " rows in the second result set")

    except:
        e = sys.exc_info()[0]
        print ("Exception: ", e)
    else:
        cursor1.close()
        cursor2.close()
        connection.close()
    input("Press Enter to continue...")

if __name__ == '__main__':
    sanity_test()

结果的输出是

代码语言:javascript
复制
connecting
test1
There are 1 rows in the first result set
test2
Exception:  <class 'mysql.connector.errors.ProgrammingError'>

我遗漏了什么?有什么技术可以获得比简洁的例外更多的信息?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-11 09:45:06

1)处理每个逻辑块的异常(例如连接,然后是cursor.create + execute),但不超过几个块。

2)获取更多描述性错误消息。

代码语言:javascript
复制
except mysql.connector.Error as err:
    print("Unexpected error : ", format(err))

3) SQL标准要求语句中字符串的单引号或双引号,例如cursor.execute("SELECT '%s'", ("foo",))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61150051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档