为什么 PyMySQL 查询没有给出任何输出? [英] Why is the PyMySQL query not giving any output?
本文介绍了为什么 PyMySQL 查询没有给出任何输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下-
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
所需的输出是
name2@mail.com usrname2
我哪里出错了?
推荐答案
我希望这将有助于用您自己的凭据替换所有凭据:
I hope this will help replace all credential with your own one:
您的代码中缺少的是您正在执行查询的打印语句,但没有对其进行任何操作,请查看 connection.commit() 语句之后的代码.这是有关如何使用 pyMySQL
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()
这篇关于为什么 PyMySQL 查询没有给出任何输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文