Python и MySQL-Connector-Python - PullRequest
       23

Python и MySQL-Connector-Python

0 голосов
/ 21 января 2019

примечание. Я использую следующую версию Python в ОС Windows:

(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, это ошибка?

Ответы [ 2 ]

0 голосов
/ 21 января 2019

Я хочу поделиться с вами моим заранее определенным классом подключения к 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'))
0 голосов
/ 21 января 2019

Согласно PEP 249 - спецификация API базы данных Python v2.0 , fetchone, fetchmany, fetchall документация ,

Исключение ошибки (или подкласса) возникает, если предыдущий вызов .execute * () не дал никакого результирующего набора или еще не было сделано никакого вызова.

fetch*() после вызова должен следовать execute Звоните.

...