Developer Resources’s Weblog

June 9, 2008

Python database access

Filed under: Python — Tags: , , , — developerresources @ 11:13 pm

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 Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.