Skip to content

Instantly share code, notes, and snippets.

@daoiqi
Last active August 29, 2015 14:12
Show Gist options
  • Save daoiqi/4cb1910bec83f8602e21 to your computer and use it in GitHub Desktop.
Save daoiqi/4cb1910bec83f8602e21 to your computer and use it in GitHub Desktop.
python mysql db lib
#!/usr/local/services/python/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
import MySQLdb.cursors
class DB:
def __init__(self):
self.con = MySQLdb.connect(host=DBHOST,port=DBPORT,user=DBUSER,passwd=DBPASSWD,db=DB)
self.cur = self.con.cursor(MySQLdb.cursors.DictCursor)
def commit(self):
self.con.commit()
def close(self):
self.cur.close()
self.con.close()
def do_sql(self,sql):
return self.cur.execute(sql)
def fetch(self,sql):
self.cur.execute(sql)
return self.cur.fetchall()
def save(self,table,myDict,isignore=False):
columns_string= '('+','.join(myDict.keys())+')'
values_string = ', '.join([ '%%(%s)s' % key for key in myDict.keys() ] )
ignore = ' IGNORE ' if isignore else '';
sql = """ INSERT %s INTO %s %s VALUES (%s) """ % ( ignore, table, columns_string,values_string)
print sql
ret = self.cur.execute(sql, myDict)
print ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment