请注意,我在Windows操作系统上使用以下版本的Python:
(venv) C:\>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
*运行下面的Python脚本,并在下面的目录中显示输出。该脚本大部分已从以下来源使用:
https://pynative.com/python-mysql-select-query-to-fetch-data/
脚本1
import mysql.connector
from mysql.connector import Error
try:
cnx = mysql.connector.connect(user='root', password='coldplay123',
host='localhost',
database='nathan_test_1')
cursor_1 = cnx.cursor()
s1="select * from dataframe"
cursor_1.execute(s1)
data1 = cursor_1.fetchall()
print("Total number of dataframes: ", cursor_1.rowcount)
for i1 in data1:
print(i1)
cursor_1.close()
except Error as e1:
print("Failure to connect ... ", e1)
cnx.close()
SCRIPT 1的输出
Total number of dataframes: 1
('a', 'b', 'c', 699)
*现在,我只更改脚本1的两行 在中间,只需将它们注释掉 并生成以下输出:
脚本2
import mysql.connector
from mysql.connector import Error
try:
cnx = mysql.connector.connect(user='root', password='coldplay123',
host='localhost',
database='nathan_test_1')
cursor_1 = cnx.cursor()
#s1="select * from nathan"
#cursor_1.execute(s1)
data1 = cursor_1.fetchall()
print("Total number of dataframes: ", cursor_1.rowcount)
for i1 in data1:
print(i1)
cursor_1.close()
except Error as e1:
print("Failure to connect ... ", e1)
cnx.close()
SCRIPT 2的输出
Failure to connect ... No result set to fetch from.
*很容易看出是什么导致了此错误,但是为什么却没有 允许'cursor_1'执行给定的SQL查询导致 错误?
答案 0 :(得分:1)
根据PEP 249 - Python Database API Specification v2.0
,fetchone
, fetchmany
, fetchall
documentation,
如果先前对.execute *()的调用未产生任何结果集或尚未发出任何调用,则会引发错误(或子类)异常。
fetch*()
呼叫后应进行execute
呼叫。
答案 1 :(得分:0)
我想向您分享我的预定义类以连接MySQL。您将为此使用PyMySQL。
import pymysql
class MySQL:
"""Connect the application to MySQL database."""
def __init__(self):
host = 'localhost'
user = 'root'
password = 'coldplay123'
database = 'nathan_test_1'
self.connection = pymysql.connect(
host=host,
user=user,
password=password,
db=database,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
autocommit=True,
)
self.cursor = self.connection.cursor()
def fetchone(self, sql, data=[]):
"""Select a single row."""
self.cursor.execute(sql, data)
result = self.cursor.fetchone()
return result
def fetchall(self, sql, data=[]):
"""Select all rows."""
self.cursor.execute(sql, data)
result = self.cursor.fetchall()
return result
def commit(self, sql, data=[]):
"""Make changes using Insert, Update, or Delete"""
self.cursor.execute(sql, data)
self.connection.commit()
return '200'
def __del__(self):
"""Closing the connection after a transaction."""
self.connection.close()
db = MySQL()
# samples
db.fetchone("select * from table where id = %s;", 2)
db.fetchall("select * from table")
db.commit("insert into table (column1, column2) values (%s, %s);",
('cell_value1', 'cell_value2'))