复制代码 代码如下:
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')
class DB(object):
def init(self,host='127.0.0.1',port=3306,user='root',passwd='123',database=''):
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.database=database
self.open=False
print 'init'
def connect(self):
if self.open == False:
print 'connect db...'
self.conn = MySQLdb.connect(host=self.host , port=self.port , user=self.user , passwd=self.passwd,charset='utf8')
self.__open = True
def executeSql(self,sql):
self.connect()
self.executor = self.conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
self.executor.execute('use '+self.database) #切换数据库
return self.__executor.execute(sql)
def executeQueryForObject(self , sql):
self.executeSql(sql)
return self.__executor.fetchone()
'''
返回key=value 字典
'''
def executeQueryAll(self , sql):
self.executeSql(sql)
return self.__executor.fetchall()
def executeUpdate(self ,sql='' , isAutoCommit=False):
c = self.executeSql(sql)
if isAutoCommit == True:
self.commit() #提交事务
return c
'''
'''
def commit(self):
self.__conn.commit() #提交事务
'''
'''
def closeDB(self):
if not self.conn is None:
print 'close db...'
self.conn.commit() #提交事务
self.__conn.close()
def print_parameters(self):
print self.user
print self.passwd
print self.host
print self.port
'''
if name == 'main':
db=DB(database='tb2013')
print db.executeQueryForObject('select count(*) as count from tb_user')
_rows = db.executeQueryAll('select userid,nick from tb_user limit 10');
print _rows
for row in _rows:
print row
print 'nick:%s' % str(row['nick'])
print db.executeUpdate(sql='update tb_user set nick=\'test\' where userid=95084397',isAutoCommit=True)
db.closeDB()
'''
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8