#encoding: utf-8
import ConfigParser
import MySQLdb
import time,os,sys,re
import traceback
'''
API 使用 :
from utils import *
db=DB()
for row in db.select('select * from pu_feed_user ;') :
print row
print db.ddl('insert into pu_feed_user (fuid,uid,foid,valid) values( 2,12,13,14 ) ')
db.close()
'''
class DB():
def __init__(self):
config = ConfigParser.RawConfigParser()
config.read('/........./...conf')
# 使用 conn = getConn()
self.conn = MySQLdb.connect(
host=config.get('db', 'host'), port=config.getint('db', 'port') ,
user=config.get('db', 'user'), passwd=config.get('db', 'passwd'),
db=config.get('db', 'database'), charset=config.get('db', 'charset'))
def select(self,sql):
cursor = self.conn.cursor ()
try :
try :
cursor.execute (sql)
return cursor.fetchall ()
except :
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,limit=2)
finally :
try:
cursor.close()
except :
cursor = None
def ddl(self,sql):
cursor = self.conn.cursor ()
try :
try :
cursor.execute (sql)
return cursor.rowcount
except :
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,limit=2)
finally :
try:
self.conn.commit ()
cursor.close()
except :
cursor = None
def close(self):
self.conn.close()
|