Home > Backend Development > Python Tutorial > Three Python methods to operate MySQL database

Three Python methods to operate MySQL database

零到壹度
Release: 2018-04-04 17:52:30
Original
1571 people have browsed it

This article mainly introduces three methods of Python operating MySQL database. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

1. How to use MySQLdb

(1) What is MySQLdb?

MySQLdb is an interface for Python to connect to the MySQL database. It implements the Python database API specification V2. 0, built on MySQL C API.

(2) Source code installationMySQLdb: https://pypi.python.org/pypi/MySQL-python

$ tar zxvf MySQL-python-*.tar.gz
$ cd MySQL-python-*
$ python setup.py build
$ python setup.py install
Copy after login

(3) MySQLdb Usage:

#!/usr/bin/env python
# coding=utf-8

import MySQLdbdef connectdb():
    print('连接到mysql服务器...')    
    # 打开数据库连接
    # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
    db = MySQLdb.connect("localhost","hp","Hp12345.","TESTDB")
    print('连接上了!')    
    return db
    
def createtable(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    
    
    # 如果存在表Sutdent先删除
    cursor.execute("DROP TABLE IF EXISTS Student")
    sql = """CREATE TABLE Student (
            ID CHAR(10) NOT NULL,
            Name CHAR(8),
            Grade INT )"""

    # 创建Sutdent表
    cursor.execute(sql)
    
def insertdb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    
    
    # SQL 插入语句
    sql = """INSERT INTO Student
         VALUES ('001', 'CZQ', 70),
                ('002', 'LHQ', 80),
                ('003', 'MQ', 90),
                ('004', 'WH', 80),
                ('005', 'HP', 70),
                ('006', 'YF', 66),
                ('007', 'TEST', 100)"""

    #sql = "INSERT INTO Student(ID, Name, Grade) \
    #    VALUES ('%s', '%s', '%d')" % \
    #    ('001', 'HP', 60)
    try:        # 执行sql语句
        cursor.execute(sql)        # 提交到数据库执行
        db.commit()    except:        # Rollback in case there is any error
        print '插入数据失败!'
        db.rollback()def querydb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    
    # SQL 查询语句
    #sql = "SELECT * FROM Student \
    #    WHERE Grade > '%d'" % (80)
    sql = "SELECT * FROM Student"
    try:        
        # 执行SQL语句
        cursor.execute(sql)        
        # 获取所有记录列表
        results = cursor.fetchall()        
        for row in results:
            ID = row[0]
            Name = row[1]
            Grade = row[2]            # 打印结果
            print "ID: %s, Name: %s, Grade: %d" % \
                (ID, Name, Grade)    
         except:        print "Error: unable to fecth data"def deletedb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 删除语句
    sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)    try:       # 执行SQL语句
       cursor.execute(sql)       # 提交修改
       db.commit()    except:        print '删除数据失败!'
        # 发生错误时回滚
        db.rollback()def updatedb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 更新语句
    sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')    try:        # 执行SQL语句
        cursor.execute(sql)        # 提交到数据库执行
        db.commit()    except:        print '更新数据失败!'
        # 发生错误时回滚
        db.rollback()def closedb(db):
    db.close()def main():
    db = connectdb()    # 连接MySQL数据库

    createtable(db)     # 创建表
    insertdb(db)        # 插入数据
    print '\n插入数据后:'
    querydb(db) 
    deletedb(db)        # 删除数据
    print '\n删除数据后:'
    querydb(db)
    updatedb(db)        # 更新数据
    print '\n更新数据后:'
    querydb(db)

    closedb(db)         # 关闭数据库if __name__ == '__main__':
    main()
Copy after login

Running results:

Three Python methods to operate MySQL database

2. Usage of PyMySQL

(1) What Is it PyMySQL?

PyMySQL is a library in Python## that is used to connect to the MySQL server. It follows the Python database API specification V2 .0, and includes the pure-Python MySQL client library.

(2) Install

PyMysql:

pip install PyMysql
Copy after login

(3) Use

PyMySQL:

#!/usr/bin/env python# coding=utf-8import pymysqldef connectdb():
    print('连接到mysql服务器...')    # 打开数据库连接
    # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
    db = pymysql.connect("localhost","hp","Hp12345.","TESTDB")
    print('连接上了!')    return dbdef createtable(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # 如果存在表Sutdent先删除
    cursor.execute("DROP TABLE IF EXISTS Student")
    sql = """CREATE TABLE Student (
            ID CHAR(10) NOT NULL,
            Name CHAR(8),
            Grade INT )"""

    # 创建Sutdent表
    cursor.execute(sql)def insertdb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 插入语句
    sql = """INSERT INTO Student
         VALUES ('001', 'CZQ', 70),
                ('002', 'LHQ', 80),
                ('003', 'MQ', 90),
                ('004', 'WH', 80),
                ('005', 'HP', 70),
                ('006', 'YF', 66),
                ('007', 'TEST', 100)"""

    #sql = "INSERT INTO Student(ID, Name, Grade) \
    #    VALUES ('%s', '%s', '%d')" % \
    #    ('001', 'HP', 60)
    try:        # 执行sql语句
        cursor.execute(sql)        # 提交到数据库执行
        db.commit()    except:        # Rollback in case there is any error
        print '插入数据失败!'
        db.rollback()def querydb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 查询语句
    #sql = "SELECT * FROM Student \
    #    WHERE Grade > '%d'" % (80)
    sql = "SELECT * FROM Student"
    try:        # 执行SQL语句
        cursor.execute(sql)        # 获取所有记录列表
        results = cursor.fetchall()        for row in results:
            ID = row[0]
            Name = row[1]
            Grade = row[2]            # 打印结果
            print "ID: %s, Name: %s, Grade: %d" % \
                (ID, Name, Grade)    except:        print "Error: unable to fecth data"def deletedb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 删除语句
    sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)    try:       # 执行SQL语句
       cursor.execute(sql)       # 提交修改
       db.commit()    except:        print '删除数据失败!'
        # 发生错误时回滚
        db.rollback()def updatedb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 更新语句
    sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')    try:        # 执行SQL语句
        cursor.execute(sql)        # 提交到数据库执行
        db.commit()    except:        print '更新数据失败!'
        # 发生错误时回滚
        db.rollback()def closedb(db):
    db.close()def main():
    db = connectdb()    # 连接MySQL数据库

    createtable(db)     # 创建表
    insertdb(db)        # 插入数据
    print '\n插入数据后:'
    querydb(db) 
    deletedb(db)        # 删除数据
    print '\n删除数据后:'
    querydb(db)
    updatedb(db)        # 更新数据
    print '\n更新数据后:'
    querydb(db)

    closedb(db)         # 关闭数据库if __name__ == '__main__':
    main()
Copy after login

Running result:

Three Python methods to operate MySQL database

3. Use of mysql.connector

(1) What is

mysql.connector?

Since the

MySQL server runs as an independent process and provides external services through the network, a MySQL driver that supports Python is required to connect to MySQL Server.

Currently, there are two

MySQL drivers:

mysql-connector-python: It is MySQL official purePython driver;

MySQL-python: It is the Python driver that encapsulates the MySQL C driver.

(2) Install

mysql.connector:

pip install mysql-connector-pythonpip install MySQL-python
Copy after login

(3) Use

mysql.connector:

#!/usr/bin/env python# coding=utf-8import mysql.connectordef connectdb():
    print('连接到mysql服务器...')    # 打开数据库连接
    # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
    db = mysql.connector.connect(user="hp", passwd="Hp12345.", database="TESTDB", use_unicode=True)
    print('连接上了!')    return dbdef createtable(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # 如果存在表Sutdent先删除
    cursor.execute("DROP TABLE IF EXISTS Student")
    sql = """CREATE TABLE Student (
            ID CHAR(10) NOT NULL,
            Name CHAR(8),
            Grade INT )"""

    # 创建Sutdent表
    cursor.execute(sql)def insertdb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 插入语句
    sql = """INSERT INTO Student
         VALUES ('001', 'CZQ', 70),
                ('002', 'LHQ', 80),
                ('003', 'MQ', 90),
                ('004', 'WH', 80),
                ('005', 'HP', 70),
                ('006', 'YF', 66),
                ('007', 'TEST', 100)"""

    #sql = "INSERT INTO Student(ID, Name, Grade) \
    #    VALUES ('%s', '%s', '%d')" % \
    #    ('001', 'HP', 60)
    try:        # 执行sql语句
        cursor.execute(sql)        # 提交到数据库执行
        db.commit()    except:        # Rollback in case there is any error
        print '插入数据失败!'
        db.rollback()def querydb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 查询语句
    #sql = "SELECT * FROM Student \
    #    WHERE Grade > '%d'" % (80)
    sql = "SELECT * FROM Student"
    try:        # 执行SQL语句
        cursor.execute(sql)        # 获取所有记录列表
        results = cursor.fetchall()        for row in results:
            ID = row[0]
            Name = row[1]
            Grade = row[2]            # 打印结果
            print "ID: %s, Name: %s, Grade: %d" % \
                (ID, Name, Grade)    except:        print "Error: unable to fecth data"def deletedb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 删除语句
    sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)    try:       # 执行SQL语句
       cursor.execute(sql)       # 提交修改
       db.commit()    except:        print '删除数据失败!'
        # 发生错误时回滚
        db.rollback()def updatedb(db):
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()    # SQL 更新语句
    sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')    try:        # 执行SQL语句
        cursor.execute(sql)        # 提交到数据库执行
        db.commit()    except:        print '更新数据失败!'
        # 发生错误时回滚
        db.rollback()def closedb(db):
    db.close()def main():
    db = connectdb()    # 连接MySQL数据库

    createtable(db)     # 创建表
    insertdb(db)        # 插入数据
    print '\n插入数据后:'
    querydb(db) 
    deletedb(db)        # 删除数据
    print '\n删除数据后:'
    querydb(db)
    updatedb(db)        # 更新数据
    print '\n更新数据后:'
    querydb(db)

    closedb(db)         # 关闭数据库if __name__ == '__main__':
    main()
Copy after login
to run the results :

Three Python methods to operate MySQL database

The above is the detailed content of Three Python methods to operate MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template