已经在数据库中创建了表并且能够查询到表里的信息,尝试移动光标也解决不了问题,无论是cursor.fetchone()还是cursor.fetchall()都报错
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import pymysql
#建立连接(客户端连接服务端)
conn = pymysql.connect(
host='',
port=3306,
user='',
password='',
database='',
charset='utf8' #不带-
)
#游标
cursor = conn.cursor(pymysql.cursors.DictCursor)
#默认游标取出来的数据是元组((),)
#DictCursor对应的数据结构{[],],如果用的是fetcheone,那么结果是{}
sql = "select * from digital_image;"
ret = cursor.execute(sql)
print(ret)
print(cursor.fetchmany())#默认一条,不写参数
print(cursor.fetchone())#取出一条
print(cursor.fetchone())#再取出一条
print(cursor.fetchall())
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
该问题可能出现的原因有很多,以下是一些可能的解决方案:
首先,需要确认SQL语句是否正确。可以在MySQL客户端中执行SQL语句,检查是否有语法错误或逻辑错误。如果SQL语句没有问题,可以尝试在Python代码中使用cursor.execute()方法执行SQL语句。
需要确认已经成功建立了数据库连接,可以使用连接对象的ping()方法检查连接是否可用。例如:
if not conn.ping(reconnect=True):
conn = pymysql.connect(
host='',
port=3306,
user='',
password='',
database='',
charset='utf8'
)
在使用fetchone()或fetchall()方法之前,需要先确认是否成功获取了查询结果。可以使用execute()方法执行SQL语句,并使用rowcount属性获取结果集的行数。例如:
ret = cursor.execute(sql)
if ret > 0:
result = cursor.fetchall()
可以使用scroll()方法移动光标到正确的位置。例如:
cursor.scroll(0, mode='absolute')
在使用fetchone()或fetchall()方法时,可能会出现异常情况,例如:数据库中不存在查询结果,或者查询结果中没有需要的字段。可以使用try-except语句捕获异常并进行处理。例如:
try:
result = cursor.fetchone()
# do something
except TypeError as e:
print('Fetch Error:', e)