+++ /dev/null
-#!/usr/bin/evn python
-
-import MySQLdb
-
-class Database:
- """ mysql database interface """
- def __init__(self, host="localhost", user="username",
- passwd="passwd", db="dbname"):
-
- self.conn = MySQLdb.connect(host=host, user=user,
- passwd = passwd, db = db)
- if not self.conn:
- raise os.error
- self.cur = self.conn.cursor(MySQLdb.cursors.DictCursor)
-
- def __del__(self):
- """ close db"""
- self.cur.close()
- self.conn.close()
-
- def update(self, table, data, condition):
-
- cond = ''
- if condition:
- cond = 'where ' + ' and '.join(["%s=\'%s\'" %(key, condition[key]) if type(condition[key]) == str else "%s=%d" %(key, condition[key]) for key in condition.keys()])
-
- set_string = ','.join(["%s=\'%s\'" %(key, data[key]) if type(data[key]) == str else "%s=%d" %(key, data[key]) for key in data.keys()])
-
- sql = ''' update %s set %s %s''' %(table, set_string, cond)
-
- self.cur.execute(sql)
- self.conn.commit()
-
- def insert(self, table, values={}):
- column_list = []
- value_list = []
- for key in values.keys():
- column_list.append(key)
- value_list.append(values[key])
-
- sql = ''' insert into %s (%s) values (%s)''' %(table, ','.join(column_list), ','.join(["\'%s\'" %s for s in value_list]))
-
- self.cur.execute(sql)
- self.conn.commit()
-
- def create_table(self, table, columns):
-
- if not table or not columns:
- return
- sql = ''' create table if not exists %s(%s) ''' %(table, ','.join(columns))
-
- self.cur.execute(sql)
-
- def columns(self, table):
-
- sql = ''' select * from %s''' %(table)
-
- self.cur.execute(sql)
- return [i[0] for i in self.cur.description]
-
- def select(self, table, data, condition=None, ext=None):
- """ select sql statement change """
- cond = ''
- if isinstance(data, list):
- select_item = ','.join(data)
- else:
- return []
-
- if condition:
- cond += 'where '
- for key in condition.keys():
- cond += ''' %s=%s and''' % (key, condition[key])
-
- if cond.endswith('and'):
- cond = cond[0:len(cond)-3]
-
- if ext:
- cond += ext
-
- sql = '''select %s from %s %s''' % (select_item, table, cond)
-
- self.cur.execute(sql)
- return self.cur.fetchall()