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 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 “””
<title>Python – Hello World</title>

print “Database version : %s ” % data


# close the mysql database connection

When viewing this page in our browser, we see:

Database version : 5.0.92-community-log

Was this article helpful? Let us know!