【问题标题】:Why is the PyMySQL query not giving any output?为什么 PyMySQL 查询没有给出任何输出?
【发布时间】:2020-09-15 07:23:03
【问题描述】:

我的代码如下-

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()

语法正确,但没有输出任何内容。终端只是打开另一个提示。 我的桌子是

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

想要的输出是

name2@mail.com              usrname2

我哪里错了?

【问题讨论】:

  • 添加结果 = cursor.fetchone()

标签: python sql pymysql


【解决方案1】:

我希望这将有助于用您自己的证书替换所有证书:

您的代码中缺少的是您正在执行查询的打印语句,但没有对其执行任何操作,请查看 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()

【讨论】:

  • @AkhibRhast 我这样做了。现在我得到一个错误结果 = cursor.fetchone() ^ TabError: 在缩进中不一致使用制表符和空格
  • @danielli12 正如错误消息清楚地表明的那样。你有一个 TabError。这意味着,由于您可能已经复制粘贴了上面的代码并且没有在文本编辑器中编写它,因此很可能您有一些空格长 4 个空格,一些空格长 1 个制表符,1 个制表符 = 4 个空格。该错误消息基本上意味着您在某处使用了一些选项卡和一些空格。要解决此问题,请确保您的文件在仅使用 4 个空格或仅使用制表符方面保持一致
猜你喜欢
  • 2019-05-14
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多