问题
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