[英]Python and MySQL-Connector-Python
note I am using the following version of Python on a Windows OS:注意我在 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.
*The following Python script below is run and the output is shown directory below it. *运行下面的 Python 脚本,输出显示在它下面的目录中。 Most of this script has been used from the following source:该脚本的大部分内容来自以下来源:
https://pynative.com/python-mysql-select-query-to-fetch-data/ https://pynative.com/python-mysql-select-query-to-fetch-data/
SCRIPT 1脚本 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()
Output of SCRIPT 1脚本 1 的输出
Total number of dataframes: 1
('a', 'b', 'c', 699)
*Now, I change just two lines from Script 1 in the middle by simply commenting them out and the following output is generated: *现在,我通过简单地注释掉中间脚本 1 中的两行,并生成以下输出:
SCRIPT 2脚本 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()
Output of SCRIPT 2脚本 2 的输出
Failure to connect ... No result set to fetch from.
*It is easy to see what causes this error, but why does not allowing 'cursor_1' to execute a given SQL query cause this error? *很容易看出导致此错误的原因,但为什么不允许“cursor_1”执行给定的 SQL 查询会导致此错误?
According to PEP 249 - Python Database API Specification v2.0 , fetchone
, fetchmany
, fetchall
documentation ,根据PEP 249 - Python 数据库 API 规范 v2.0 、 fetchone
、 fetchmany
、 fetchall
文档,
An Error (or subclass) exception is raised if the previous call to .execute*() did not produce any result set or no call was issued yet.如果先前对 .execute*() 的调用未产生任何结果集或尚未发出任何调用,则会引发错误(或子类)异常。
fetch*()
call should be followed by execute
call. fetch*()
调用之后应该是execute
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.