Python access to common class instances of MySQL encapsulation _python

Source: Internet
Author: User
Tags mysql functions

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.