MySQL is the world's most popular open source database. Most web developers are using MySQL with php. Python can handle this database by using a module MySQL-Python. For connecting to MySQL you need MySQL-Python module,you can get it from http://sourceforge.net/projects/mysql-python .If you have a fedora or Debian Linux installation is bit easy.For installing MySQL-python in fedora type


#yum install MySQL-python


For installing in Debian do

#apt-get install MySQL-python

After installing the module we are going to do some codings for connecting to the database.

import MySQLdb

try:
conn = MySQLdb.connect (host = "yourhost",
user = "user",
passwd = "password",
db = "database")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])


The above script will connect to database so you have to provide necessary login informations such as host name,user name,password and database name.

For executing SQL commands we hace to make a cursor.For making a cursor use the following code

cursor = conn.cursor ()

MySQL commands can execute using this cursor for example see the below code

cursor.execute ("""INSERT INTO clg_register (roll_no, name, age)VALUES(%s, %s,%s,%s)""",("39","Nikhil","18"))

You can use variables in the script instead of given values in the cursor.execute() code.Any MySQL command can execute using this code.After executing MySQL commands close the connection to the database by using the below code

cursor.close ()
conn.close ()


A sample program is given below to insert data into a school register database.



import MySQLdb


try:
conn = MySQLdb.connect (host = "localhost",
user = "root",
passwd = "password",
db = "college_register")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
cursor = conn.cursor ()
cursor.execute ("""
CREATE TABLE Person
(
LastName varchar(30),
FirstName varchar(20),
Address varchar(30),
Age int(3)
)
""")

cursor.execute ("""INSERT INTO Person(LastName,FirstNAME,Address,Age) VALUES("Vishnu","Nikhil","India,Kerala","18")""")
cursor.close ()
conn.close ()