>  기사  >  백엔드 개발  >  MySQL 데이터베이스를 작동하는 세 가지 Python 방법

MySQL 데이터베이스를 작동하는 세 가지 Python 방법

零到壹度
零到壹度원래의
2018-04-04 17:52:301457검색

이 기사에서는 Python에서 MySQL 데이터베이스를 운영하는 세 가지 방법을 주로 소개합니다. 편집자는 이것이 꽤 좋다고 생각하므로 지금 공유하고 참고용으로 제공하겠습니다. 에디터를 따라가며 함께 살펴볼까요

1. MySQLdb

의 사용법(1) MySQLdb란?

MySQLdbMySQL 데이터베이스에 연결하기 위한 Python용 인터페이스로 Python 데이터베이스 API 사양 V2.0을 구현하고 MySQL C API를 기반으로 구축되었습니다.

(2) 소스 코드 설치MySQLdb: https://pypi.python.org/pypi/MySQL-python

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

(3) MySQLdb 사용법:

#!/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()

실행 결과:

MySQL 데이터베이스를 작동하는 세 가지 Python 방법

2. PyMySQL

의 활용(1) PyMySQL이란?

PyMySQLMySQL 서버에 연결하는 데 사용되는 Python의 라이브러리로, Python 데이터베이스 API 사양 V2.0을 따르며 pure-Python MySQL 클라이언트 라이브러리를 포함합니다.

(2) PyMysql 설치:

pip install PyMysql

(3) 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()

사용 실행 결과:

MySQL 데이터베이스를 작동하는 세 가지 Python 방법

3.mysql.connector

사용이란? mysql .커넥터?

MySQL 서버는 독립적인 프로세스로 실행되며 네트워크를 통해 외부 서비스를 제공하므로 MySQL 서버에 연결하려면 PythonMySQL 드라이버를 지원해야 합니다.

현재 두 가지 MySQL 드라이버가 있습니다.

mysql-connector-python: MySQL 공식 순수 Python 드라이버입니다.

MySQL-python: 캡슐화되어 있습니다. MySQL C 드라이버 Python 드라이버입니다.

(2) mysql.connector 설치:

pip install mysql-connector-pythonpip install MySQL-python

(3) 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()

사용 실행 결과:

MySQL 데이터베이스를 작동하는 세 가지 Python 방법

위 내용은 MySQL 데이터베이스를 작동하는 세 가지 Python 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.