Why is the PyMySQL query not giving any output?

好久不见. 提交于 2020-06-29 05:08:36

问题


My code is as follows-

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

The syntax is correct, but it isn't outputting anything. Terminal simply opens another prompt. My table is

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

The desired output is

name2@mail.com              usrname2

Where am I going wrong?


回答1:


I hope this will help replace all credential with your own one:

What you are missing in your code is a print statement you are executing a query, but not doing anything with it, take a look at the code that is after the connection.commit() statement. Here is documentation and example on how to use 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()


来源:https://stackoverflow.com/questions/62056897/why-is-the-pymysql-query-not-giving-any-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!