Import class system and MySQLdb
import sys
import MySQLdb
Connect to database - if an error occures display message and exit.
def __init__(self,host,user,password,database):
self.database_connect(host,user,password,database)
return
def database_connect(self,host,user,password,database):
try:
self.conn = MySQLdb.connect(host=host, user=user, passwd=password, db=database)
except MySQLdb.Error, e:
print "Connection error\n%d: %s\n" % (e.args[0],e.args[1])
sys.exit(1)
return
def cursor_return(self):
try:
self.conn.ping()
except:
self.database_connect()
return self.conn.cursor()
Get one result from database.
def result_return(self,query):
kursor = self.cursor_return()
try:
kursor.execute(query)
except MySQLdb.Error, e:
print "Query error\n%s\n%d: %s\n" % (query,e.args[0],e.args[1])
sys.exit(1)
result = kursor.fetchone()
kursor.close()
return result
Get results from database.
def results_return(self,query):
kursor = self.cursor_return()
try:
kursor.execute(query)
except MySQLdb.Error, e:
print "Query error\n%s\n%d: %s\n" % (query,e.args[0],e.args[1])
sys.exit(1)
results = kursor.fetchall()
kursor.close()
return results
Execute query.
def execute_query(self,query):
kursor = self.cursor_return()
try:
kursor.execute(query)
except MySQLdb.Error, e:
print "Query error\n%s\n%d: %s\n" % (query,e.args[0],e.args[1])
sys.exit(1)
kursor.close()
return
How to us it?
import DBMySQL
c=DBMySQL.DataBase("hostname","username","password","database_example")
t = c.results_return("SELECT id,title FROM films;")
for (i,j) in t:
print "%s %s " % (i,j)
1 Transporter
2 Taxi 1
3 Taxi 2
4 Taxi 3
5 Alien 2
6 Alien 1
7 Alien 3
8 Alien 4
9 The Thing
10 Reservoir dogs
Source code