【发布时间】: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