While most users will not have a need to use Python to connect to their MySQL database, there have been a few times when we've had questions about how to do that with Python.

At this point in the process you should already created a MySQL database and have a user assigned to that database.

Database Settings for Python Script

You will need the following settings for your script. Please note that the settings we are including below are for our testing purposes, please replace these with your settings (database host should stay the same).

database name: whhsup5_python
database user: whhsup5_python
database password: pytest
database host: localhost

Once we have the database setup, we can create our script and save it to the cgi-bin folder as pythontest.py (name your file however you like, just remember the .py extension). Once the file has been created, change the fle permissions to 755 (as all files in the cgi-bin should be).

This script will connect to and run the SELECT VERSION(), command which will show us what version of MySQL our database is running.

Python Script

#!/usr/bin/env python

import MySQLdb

# connect to the database
db = MySQLdb.connect("localhost","whhsup5_python","pytest","whhsup5_python" )

# setup a cursor object using cursor() method
cursor = db.cursor()

# run a sql question
cursor.execute("SELECT VERSION()")

# grab one result
data = cursor.fetchone()

# begin printing data to the screen
print "Content-Type: text/html"

print

print """\
<html>
<head>
<title>Python - Hello World</title>
</head>
<body>
"""

print "Database version : %s " % data

print"""\
</body>
</html>
"""

# close the mysql database connection
db.close()

Now, let's bring up pythontest.py in a browser and we should see:

python-connect-to-sql-db

Congratulations, you've just used Python to connect to your MySQL database!

Did you find this article helpful?

Login to comment.

Your Opinion Matters

... but we need to know what you're thinking!

I'm Christi Nickerson, your friendly Community Support technician, and I wrote the article you're looking at now. I like to think it's perfect, but I'm sure you have some suggestions. Please, let me know what they are!

Feedback
Your Email Address
Because we'd like to talk with you!

Have a Question?

If you need some help, submit your question to our Community! We guarantee a response within 60 minutes (8am - 9pm EST, Monday - Friday)

Recent Questions

  1. Site under brute force attack
  2. URLs in Installation of WordPress Don't Redirect
  3. Choosing a Directory With WordPress

Support Center Search

Current Customers

Email: support@WebHostingHub.com Ticket: Submit a Support Ticket
Call: 877-595-4HUB (4482)
757-416-6627 (Intl.)
Chat: Click To Chat Now

Ask the Community

Get help with your questions from our community of like-minded hosting users and Web Hosting Hub Staff.

Not a Customer?

Get web hosting from a company that is here to help.