Copy Code code as follows:
#-*-Coding:utf-8-*-
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 ()
'
return to Key=value dictionary
'
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 () #提交事务
'
#关闭数据库, releasing resources
'
def Closedb (self):
if not Self.__conn are 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 ')
#db. Print_parameters ()
#db. ExecuteSQL (' select * from Tb_user ')
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 ()
'''