I usually use two MySQL functions: Query and update, the following is their own commonly used functions of the package, we copy the past can be used directly.
FileName: dbutil.py
| The code is as follows |
Copy Code |
#-*-Encoding:utf8-*- ''' @author: Crazyant.net @version: 2013-10-22
Encapsulated MySQL Common functions '''
Import MySQLdb
Class DB (): def __init__ (self, db_host, Db_port, Db_user, Db_pwd, db_name): Self. Db_host = Db_host Self. Db_port = Db_port Self. Db_user = Db_user Self. Db_pwd = Db_pwd Self. Db_name = db_name
Self.conn = Self.getconnection ()
def getconnection (self): Return MySQLdb.connect ( Host=self. Db_host, #设置MYSQL地址 Port=self. Db_port, #设置端口号 User=self. Db_user, #设置用户名 Passwd=self. Db_pwd, #设置密码 Db=self. Db_name, #数据库名 charset= ' UTF8 ' #设置编码 )
|
def query (self, sqlstring):
Cursor=self.conn.cursor ()
Cursor.execute (SqlString)
Returndata=cursor.fetchall ()
Cursor.close ()
Self.conn.close ()
Return Returndata
def update (self, sqlstring):
Cursor=self.conn.cursor ()
Cursor.execute (SqlString)
Self.conn.commit ()
Cursor.close ()
Self.conn.close ()
If __name__== "__main__":
Db=db (' 127.0.0.1 ', 3306, ' root ', ', ', ' WordPress ')
Print Db.query ("Show Tables;")
uses the method to execute a SELECT statement using query and obtain the results, or to use update for inserts, deletes, and so on.