【问题标题】:Cant connect to mysql from python无法从python连接到mysql
【发布时间】:2022-01-19 11:42:24
【问题描述】:

我有这段代码正在接收来自 pubnub 的调用,它接收文本,我想将该文本存储在 mysql 数据库中

class MySubscribeCallback(SubscribeCallback):
    def message(self, pubnub, message):
        messageArray = message.dict
        print(messageArray['message']['sender'])
        cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)

我在尝试运行我的代码时不断收到此错误

cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
AttributeError: 'NoneType' object has no attribute 'cursor'

关于问题出在哪里的任何想法?

【问题讨论】:

  • 通过在控制台中打印来确定 db 包含的内容。显然, db 没有“连接”对象。我认为您可能想要“db.cursor”而不是“db.connection.cursor”
  • 我检查了数据库并打印了:
  • 好的,应该是这样的:我把它放在一个答案中,因为这里的代码格式太糟糕了

标签: python mysql iot pubnub


【解决方案1】:

您的代码必须如下所示:

from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)
db = MySQL(app)

# Your class/method where db.connection.cursor() is called

if __name__ == '__main__':
    app.run() # or app.run(debug=True)

【讨论】:

  • 我已经与数据库建立连接并在其他功能中运行sql代码
【解决方案2】:

按照以下步骤操作:

  1. 您需要使用以下命令安装 mysql 连接器

python -m pip install mysql-connector-python

  1. 以下代码是安装包后可以使用的简单连接
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

print(mydb) 

【讨论】:

  • 我正在使用 Flask 框架
猜你喜欢
  • 2017-04-09
  • 1970-01-01
  • 2021-03-21
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2011-06-19
相关资源
最近更新 更多