Sep 20, 2010

Database connect via python

fgTo connect to a database we must first install a special module to communicate with the database.If the database is MYSQL you must install MySQLdb module.

To do that you must type;

yum install MySQL-python

After the instalation you shoyld be able to; >>>import MySQLdb

If this thing won't give any error you can continue.

First we must import modules which we need to runour script. So;

import sys
import MySQLdb

Then we must connect to the databace and to do that;

try:
conn=MySQLdb.connect(host="",user="",passwd="",db="")

except MySQLdb.Error,e:
print "Can not connect to the database"
sys.exit(1)

Now we are connected to the database. Now we need to send querys to our database.

Try:
cursor=conn.cursor()
cursor.execute(""" your query """)
cursor.close()
except MySQLdb.Error,e:
priint "Some error...!!!"
sys.exit(1)

You had done all the things for now. So you shoul close the connection which you open.

conn.commit()
conn.close()
sys.exit()

No comments:

Post a Comment

Your comments are always welcome ...