为什么pymysql查询不提供任何输出?

noj0wjuj  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(426)

我的代码如下-

import pymysql
connection = pymysql.connect(host='localhost',user='root',password='',db='form',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "SELECT * FROM info ORDER BY `id` DESC LIMIT 1"
        cursor.execute(sql)

finally:
        connection.close()

语法是正确的,但是它没有输出任何东西。终端只需打开另一个提示符。我的table是

email                  username                       id
name@mail.com          usrname1                        1
name2@mail.com         usrname2                        2

所需输出为

name2@mail.com              usrname2

我哪里出错了?

vfhzx4xs

vfhzx4xs1#

我希望这将有助于用您自己的凭据替换所有凭据:
代码中缺少的是一个print语句,您正在执行一个查询,但没有对它执行任何操作,请查看connection.commit()语句后面的代码。下面是关于如何使用pymysql的文档和示例

import pymysql.cursors

# Connect to the database

connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

相关问题