This example describes Python's common classes for accessing the MySQL package. Share to everyone for your reference. Specifically as follows:
Python access to MySQL is simpler, the following is a very simple Python access MySQL database class.
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
Copy Code code as follows:
#-*-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;")
Use the method to execute a SELECT statement using query and obtain the results, or use update for INSERT, delete, and so on, with the following main function.
I hope this article will help you with your Python programming.