Greg Peckory
Greg Peckory

Reputation: 8058

Using Python with MySQL

I've set up an Application on OpenShift like this:

enter image description here

I am using Flask with python on the server-side.

Note: I just need to connect Python to MySQL, Flask is irrelevant.

My Hello World program works fine:

flaskapp.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello World!"

if __name__ == '__main__':
    app.run()

In the requirements.txt the following dependency was added: Flask==0.10.1

I'm wondering is it necessary to add the MySQL dependency, like this: MySQLdb==5.5?

I've tried importing and using MySQL in flaskapp.py like this:

from flask import Flask
import mysql # I tried MySQLdb as well

app = Flask(__name__)

@app.route('/')
def hello_world():

    output = ''

    db = mysql.connect(host="mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/",    # your host, usually localhost
                     user="adminIChJ87N",   
                     passwd="mypassword",  
                     db="python")  

    cur = db.cursor()
    cur.execute("SELECT * FROM MyTable")

    for row in cur.fetchall():
        output+=row[0]

    db.close()  
    return output

if __name__ == '__main__':
    app.run()

How exactly do I use this MySQL database with Python? There seems to be no code on Openshift's website

Upvotes: 1

Views: 2298

Answers (1)

JulienD
JulienD

Reputation: 7293

The name of the package for MySQLdb is mysqlclient (if you want it to work with Python3, otherwise it is a fork of MySQL-python). So this is what you need to put in the dependencies. Run pip install mysqlclient to try it.

Upvotes: 2

Related Questions