Saturday, June 14, 2008

Python database access

Here is an example of how to connect to a MysqlDB using python.
#!/usr/bin/python

import MySQLdb
import sys

class Table:
def __init__(self, db, name):
self.db = db
self.name = name
self.dbc = self.db.cursor()

def execute(self):
query = "select 1,2 from you_table "
self.dbc.execute(query)
return self.dbc.fetchall()

def next(self):
return self.dbc.fetchone()

db = MySQLdb.connect(host="<your host>",user="<your username>", db="<your db>", passwd=<your passwd>)
event_table = Table(db, "event_table")

records = event_table.execute()
for r in records:
print str(r[0])+","+str(r[1])

No comments: