【问题标题】:Python and MySQL - fetchall() doesn't show any resultPython 和 MySQL - fetchall() 不显示任何结果
【发布时间】:2020-04-19 19:58:29
【问题描述】:

我在从 Python 代码中获取查询结果时遇到问题。与数据库的连接似乎有效,但我总是收到错误:

"InterfaceError: No result set to fetch from."

有人可以帮我解决我的问题吗?谢谢!!!

cnx = mysql.connector.connect(
    host="127.0.0.1" , 
    user="root" , 
    passwd="*****",
    db="testdb"
)
cursor = cnx.cursor()
query = ("Select * from employee ;")

cursor.execute(query)

row = cursor.fetchall()

【问题讨论】:

  • 试试query = "Select * from employee" 并添加print(cursor.fetchall())

标签: python mysql mysql-python fetchall


【解决方案1】:

如果你的问题还是没有解决,可以考虑更换python mysql驱动包,使用pymysql。 可以这样写代码

#!/usr/bin/python
import  pymysql

db = pymysql.connect(host="localhost",    # your host, usually localhost
                     user="test",         # your username
                     passwd="test",  # your password
                     db="test")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

query = ("SELECT * FROM employee")

# Use all the SQL you like
cur.execute(query)

# print all the first cell of all the rows
for row in cur.fetchall():
    print(row[0])

db.close()

这样应该可以找到你想要的结果

【讨论】:

    【解决方案2】:

    将此添加到您的代码中

    for i in row:
        print(i)
    

    你没有打印任何东西,这就是为什么这不起作用 这将在单独的行中打印每一行

    【讨论】:

    • 虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,纯代码的答案没有用处。
    【解决方案3】:

    首先尝试打印(行),如果失败尝试使用for循环执行,删除选择查询语句中的分号

    cursor = connection.cursor()
    rows = cursor.execute('SELECT * FROM [DBname].[dbo].TableName where update_status is null ').fetchall()
    
    for row in rows:
        ds = row[0]
        state = row[1]
    

    这里的row[0]代表数据库中的第一个列名 & row[1] 代表数据库中的第二个列名,以此类推

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多