2

I have a MySQL database with stock market quotes. I'm trying to create a python script to connect to the database and query it. Here is my python script...

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost:8889/database_name'
db = SQLAlchemy(app)


class Stocks(db.Model):
    __tablename__ = 'stocks'
    stock_id = db.Column('stock_id', db.Integer, primary_key=True)
    adj_close = db.Column('adj_close', db.Float)
    close = db.Column('close', db.Float)
    date = db.Column('date', db.Date)
    high = db.Column('high', db.Float)
    low = db.Column('low', db.Float)
    open = db.Column('open', db.Float)
    symbol = db.Column('symbol', db.String(10))
    volume = db.Column('volume ', db.Float)

I'm trying to query the data base utilizing the python console with the following commands...

>>>from file.py import Stocks
>>>data = Stocks.query.all()

And I get the following error...

ImportError: No module named MySQLdb

I'm running python 2.7.12

If I run this code with python 3.5.2 I get the following error...

ImportError: No module named 'MySQLdb'

If I try to install MySQLdb I get the following...

Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb

How can I fix this?

0

1 Answer 1

3

With a "mysql://..." connection string, SQLAlchemy will use the MySQL-python to connect by default, so you need to install that package using pip.

pip install MySQL-python

Alternatively, you can use another library to connect, such as PyMySQL (MySQL-python is no longer actively developed). Just change your connection string:

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:password@localhost:8889/database_name'

To install PyMySQL:

pip install PyMySQL
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.