How To Simply Connect Python To MySQL On Your Site

Nearly all the visitors to this website are interested in how to
integrate the python programming language into their website.

We are going through a website I originally build in PHP and MySQL, and reconstruct the site using python and MySQL.

Interesting. This will give some good insight into python concepts.

In this post, I am going to show you how to simply connect your Python webpage to the MySQL server on your website.

In this small bit of code I am demonstrating a how you can connect your python webpage to your MySQL server.

#!/usr/bin/python

import MySQLdb

def dbconnect(): 
    conn = MySQLdb.connect('localhost', 'username','password', 'database')

    cursor = conn.cursor()

    sql="SELECT * FROM tblContestants"

    cursor.execute(sql)

    #any print items need to be below this line:                             
    print "Content-type: text/html\n\n";
    
    for row in cursor:
        #this prints out the 1st column
        print(row[0]) 

#start here:
dbconnect()

With Python, you can import “modules”. In this case to connect to the MySQL server I’m importing the “MySQLdb” module. I can choose to use the code in this module without trying to recode all of the MySQL logic, which will probably take me months! Trust me, this is easier :).

Note: All procedures in Python begin with the “def” keyword.

Now that new “dbconnect” procedure can be used each time I need to make a connection to the database.

…and there are curly brackets around your procedures, just make sure you make the proper indenting, or else your code WILL FAIL.

Indenting is very important in Python. To make sure your indenting is correct start out with the “IDLE” text editing program that should have come with your installation of Python. I have also used “Dr. Python” in the past.

def dbconnect(): 

My “cursor” is like my recordset, and I can loop through my recordset like this:

    
        print "

These are contestants from a MySQL table:

" for row in cursor: #this prints out the 1st column print(row[0])

Remember that since we are outputting text to the screen, this needs to be present:

print "Content-type: text/html\n\n";

PS. If running your file gives you a 500 error, make sure you set the file permissions to 755.

Here it is in action:

http://pythoninhtmlexamples.com/files/mysql.py

Facebooktwitterredditpinterestlinkedinmail
Tags: , ,
Previous Post

How To Make A Python Data Entry Form

Next Post

Simple Python Variables Examples