Wednesday, 17 July 2013

Using Python to access MySQL Database

Setup Apache2.4 for Python

In Apache httpd.conf:

edit the Options field, add in ExecCGI.

Options Indexes FollowSymLinks ExecCGI

edit the AddHandler field, add in .py

AddHandler cgi-script .cgi .py

Run Python script in Web browser

If you use Python3 interpreter, the script must be written in Python3 version.

The test.py script to output the Hello World on the browser. Notice the first line #!/Python33/python is the syntax to refer to Windows Python interpreter.

#!/Python33/python

# enable debugging
import cgitb

cgitb.enable()

print("Content-Type: text/plain;charset=utf-8")
print()

print("Hello World!")


The script to output cgi environment.

#!/Python33/python

import cgi
cgi.test()

If you want to access to MySQL database from python, here is another simple script to do so. In the script, the database is called "test", the table is called "doctor".

#!/Python33/python

import datetime
import mysql.connector

config = {
  'user': 'root',
  'password': 'root',
  'host': '127.0.0.1',
  'database': 'test',
  'raise_on_warnings': True,
}

print("Content-Type: text/plain;charset=utf-8")
print()
print("read doctor database")

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

query = ("SELECT * FROM doctor")      

cursor.execute(query)

results = cursor.fetchall()
print(results)

cursor.close()
cnx.close()


No comments:

Post a Comment