How to use Python to connect to a database

Using Python, you can connect and run queries against a MySQL database on your server.

In this example, we’ve created a test script named test_db.py and placed it in our cgi-bin folder. We also updated the file’s permissions to 755.

We also used the following settings within the code:

  • database name: inmoti6_pytest
  • database user: inmoti6_pytest
  • database password: pytest
  • database host: localhost

We’re connecting to the database and running SELECT VERSION(), which shows us which version of MySQL we are running.

Note: You must have the following line of code at the top of your your .htaccess file to be able to run Python scripts:
AddHandler cgi-script .cgi .pl .py

#!/usr/bin/env python

import MySQLdb

# connect to the database
db = MySQLdb.connect(“localhost”,”inmoti6_pytest”,”pytest”,”inmoti6_pytest” )

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

# run an 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()

When viewing this page in our browser, we see:

Database version : 5.0.92-community-log

Leave a Reply