【问题标题】:MySql Class Object function error - pythonMySql 类对象函数错误 - python
【发布时间】:2021-08-03 09:32:26
【问题描述】:

我正在使用类对象订阅数据流,以使用 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 的一个实例来创建连接,同时调用ticker,最后在进行插入时。但是你是 Stream 的不同实例来做所有这些。

标签: python mysql function class


【解决方案1】:

当您执行Stream() 时,您正在创建一个Stream 的实例,该实例具有自己的cnxcursor 值集。您在多个位置创建了 Stream 实例,并希望它们指向单个实例,但事实并非如此。

在下面的sn-p中

s1 = Stream()
s2 = Stream()

s1 和 s2 指向 Stream 的不同实例。所以,s1的cnxcur会和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())

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多