MySql类对象函数错误-python

MySql类对象函数错误-python,python,mysql,function,class,Python,Mysql,Function,Class,我使用类对象订阅数据流,以使用MySql将数据插入数据库。有人能解释一下我的错误是从哪里来的吗 回溯错误: File "/media/.........../stream.py", line 51, in database_insert self.cursor.execute(self.insert, self.values) AttributeError: 'NoneType' object has no attribute 'execute' ***我已经注释掉

我使用类对象订阅数据流,以使用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()
    

当您执行
Stream()
操作时,您正在创建一个
Stream
的实例,其中包含
cnx
cursor
的一组值。您已经在多个位置创建了
Stream
实例,并希望它们指向一个实例,但实际情况并非如此

在下面的片段中

s1 = Stream()
s2 = Stream()
s1和s2指向
流的不同实例。因此,s1的
cnx
cur
将不同于s2

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

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())

在调用ticker和最后执行insert时,您必须使用
流的一个实例来创建连接。但是您可以使用
流的不同实例来执行所有这些操作。