python - 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()
解决方案
当您这样做时Stream()
,您正在创建一个 的实例,该实例Stream
具有自己的 和 值cnx
集cursor
。您已经Stream
在多个地方创建了实例,并希望它们指向一个实例,但事实并非如此。
在下面的片段中
s1 = Stream()
s2 = Stream()
s1 和 s2 指向 的不同实例Stream
。因此,s1 的cnx
andcur
将不同于 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())
推荐阅读
- c# - 在 Windows 身份验证 IIS 8.5 中拒绝用户
- javascript - 在 Django 上渲染一个使用的 API 到 React 前端
- php - 需要一个特定的包提交 - composer 似乎忽略了 composer.json 的要求
- python - 在后台启动的 tshark 任务不会生成任何文件
- c++ - 当我尝试加载 PNG 纹理 (Direct3D 11) 时出现“找不到组件”错误
- javascript - 将js脚本添加到django项目的问题
- html - 使用 R 跨多个链接进行网络抓取
- ios - 防止 SwiftUI 子视图重绘
- swift - Editbutton 在 SwiftUI 中以一种有趣的方式从 List 中删除项目(带有绑定)
- javascript - 如何从客户端访问服务器目录中的文件?