Home > Software design >  Cant connect to mysql from python
Cant connect to mysql from python

Time:12-16

I have this code which is receiving a call from pubnub, it takes in text and I want to store that text in a mysql database

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

I keep receiving this error when trying to run my code

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

Any ideas on where the problem is?

CodePudding user response:

Your code must looks like that :

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)

CodePudding user response:

Kindly specify which framework you are using or follow these steps below:

  1. You will need to install mysql connector using the command below

python -m pip install mysql-connector-python

  1. The below code is a simple connection you can use after installing the package
import mysql.connector

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

print(mydb) 
  • Related