首页 > 解决方案 > MySql 类对象函数错误 - python

问题描述

我正在使用类对象订阅数据流,以使用 MySql 将数据插入数据库。谁能阐明我的错误来自哪里?

回溯错误:

File "/media/.........../stream.py", line 51, in database_insert
    self.cursor.execute(self.insert, self.values)
AttributeError: 'NoneType' object has no attribute 'execute'

*** 我将 while 循环注释掉了,因为它更容易。相反,我在其位置使用示例 json 字符串,直到我的脚本准备好运行。

import asyncio
from binance import AsyncClient, BinanceSocketManager
import mysql.connector
from mysql.connector import errorcode
import datetime
import json

class Stream:
    def __init__(self):
        self.cnx = None
        self.cursor = None
        
    def database_connect(self):
        self.cnx = mysql.connector.connect(user='root',
                                    password='',
                                    host='localhost',
                                    database='')

        self.cursor = self.cnx.cursor() 
        return self.cursor

    def database_disconnect(self):
        self.cnx = mysql.connector.connect(user='root',
                                    password='',
                                    host='localhost',
                                    database='')

        self.close = self.cnx.close()
        
    def accounting_insert(self, query, data_tuple):   
        self.cursor.execute(query, data_tuple)
        self.cnx.commit()
        self.cnx.close()
        
        print('Data has been successfully inserted into the database.')   

    def database_insert(self, ticker, timestamp, price):
        self.insert = ("INSERT INTO data_" + ticker + " "
               "(timestamp, price) "
               "VALUES (%s, %s)")
        self.values = (int(timestamp), float(price))
        self.cursor.execute(self.insert, self.values)
        self.cnx.commit()
        self.cnx.close()
        print("Values Inserted.")

    def ticker(self, res):
        longTicker = res['data']['s']
        if longTicker == 'BTCUSDT':
            return 'BTC'
        elif longTicker == 'BCHUSDT':
            return 'BCH'

    def timestamp(self, res):
        return res['data']['E']

    def price(self, res):
        return res['data']['p']

try:
    Stream().database_connect()
    
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
else:
    print("success")
    async def main():
        client = await AsyncClient.create()
        bm = BinanceSocketManager(client)
        # pass a list of stream names
        ms = bm.multiplex_socket(['btcusdt@trade', 'bchusdt@trade'])
        # then start receiving messages
        async with ms as tscm:
            #while True:
            #res = await tscm.recv()
            #print(res)
            res = {'stream': 'btcusdt@trade', 'data': {'e': 'trade', 'E': 1620716700815, 's': 'BTCUSDT', 't': 272261278, 'p': '65551.60000000', 'q': '25.76580000', 'b': 2142679715, 'a': 2142679312, 'T': 1620716700814, 'm': False, 'M': True}}

            ticker = Stream().ticker(res)
            timestamp = Stream().timestamp(res)
            price = Stream().price(res)
            print("Ticker: " + str(ticker) + "   " + "Time: " + str(timestamp) + "   " + "Price: $" + str(price))
            
            Stream().database_insert(ticker, timestamp, price)
                

        await client.close_connection()

    if __name__ == "__main__":

        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())

    Stream().database_disconnect()
    

标签: pythonmysqlfunctionclass

解决方案


当您这样做时Stream(),您正在创建一个 的实例,该实例Stream具有自己的 和 值cnxcursor。您已经Stream在多个地方创建了实例,并希望它们指向一个实例,但事实并非如此。

在下面的片段中

s1 = Stream()
s2 = Stream()

s1 和 s2 指向 的不同实例Stream。因此,s1 的cnxandcur将不同于 s2 的 and。

您必须进行以下更改才能使您的代码正常工作。

try:
    stream = Stream().database_connect()
    
except mysql.connector.Error as err:
    .....
    .....
else:
    print("success")
    async def main():
        client = await AsyncClient.create()
        ....
        ....
        async with ms as tscm:
            ....
            ....
            ticker = stream.ticker(res)
            timestamp = stream.timestamp(res)
            price = stream.price(res)
            print("Ticker: " + str(ticker) + "   " + "Time: " + str(timestamp) + "   " + "Price: $" + str(price))
            
            stream.database_insert(ticker, timestamp, price)
            
            stream.database_disconnect()

        await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

推荐阅读