This article describes how to connect python to mysql and submit mysql transactions. For more information, see the following code:
#-*-Coding: UTF-8 -*-
Import sys
Import MySQLdb
Reload (sys)
Sys. setdefaultencoding ('utf-8 ')
Class DB (object ):
Def _ init _ (self, host = '192. 0.0.1 ', port = 127, user = 'root', passwd = '2016', 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.20.executor.exe cute ('use' + self. _ database) # Switch the database
Return self.20.executor.exe cute (SQL)
Def executeQueryForObject (self, SQL ):
Self. _ executeSql _ (SQL)
Return self. _ executor. fetchone ()
'''
Returns the 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 () # submit a transaction
Return c
'''
# Commit transactions
'''
Def commit (self ):
Self. _ conn. commit () # submit a transaction
'''
# Shut down the database and release resources
'''
Def closeDB (self ):
If not self. _ conn is None:
Print 'close db ...'
Self. _ conn. commit () # submit a transaction
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 ()
Mongodb.exe cuteSql ('select * from tb_user ')
Print db.exe cuteQueryForObject ('select count (*) as count from tb_user ')
_ Rows = db.exe cuteQueryAll ('select userid, nick from tb_user limit 10 ');
Print _ rows
For row in _ rows:
Print row
Print 'Nick: % s' % str (row ['Nick '])
Print db.exe cuteUpdate (SQL = 'Update tb_user set nick = \ 'test \ 'where userid = 95084397', isAutoCommit = True)
Db. closeDB ()
'''