基于Python下MySQL数据库驱动

由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。

1.mysql-connector-python

​ mysql-connector-python是MySQL官方提供的驱动。

  1. 安装:

    pip3 install mysql-connector

  2. 使用:

    2.1 创建数据库连接,执行SQL查询数据;

    import mysql.connector
    
    # 创建数据库连接配置
    config = {
        "host":"rm-a.mysql.rds.aliyuncs.com",
        "port":3306,
        "user":"root",
        "password":"psw",
        "db":"examin_prod",
        "charset":"utf8"}
    
    def getExaminReportMCY(agency_id='123456789', examin_date='2021-04-01'):
        '''
        mysql-connector-python
        '''
        # 创建数据库连接
        conn = mysql.connector.connect(**config)
        # 得到一个可以执行SQL语句的游标对象
        cursor = conn.cursor(dictionary=True)
        # 使用 execute()  方法执行 SQL 查询 
        # format_map 格式化字符串拼接SQL参数
        cursor.execute(SQL_EXAMIN_REPORT.format_map({"agency_id": agency_id, "examin_date": examin_date}))
        # 使用 fetchall() 方法获取所有数据
        data = cursor.fetchall()
        # 关闭游标
        cursor.close()
        # 关闭数据库连接
        conn.close()
    
        return data
      
    # SQL
    SQL_EXAMIN_REPORT = '''SELECT
        ther.id,
    FROM
        t_health_examin_record
    WHERE
        agency_id = '{agency_id}' AND examin_date = '{examin_date} 00:00:00'
    '''
    

2.pymysql

​ pymsql是Python中用于连接 MySQL 服务器的一个库,目前pymysql支持python3.x。

  1. 安装:

    pip3 install pymysql

  2. 使用:

    2.1 创建数据库连接,执行SQL查询数据;

    import pymysql
    
    def getExaminReport(agency_id='123456789', examin_date='2021-04-01'):
        # 创建数据库连接
        conn = pymysql.connect(host='rm-a.mysql.rds.aliyuncs.com',
                                port=3306,
                                user='root',
                                password='psw',
                                db='examin_prod',
                                charset='utf8')
    
        # 创建游标对象,得到一个可以执行SQL语句的游标对象
        #cursor = conn.cursor()  # 执行完毕返回的结果集默认以元组显示
        # 使用 cursor(cursor=pymysql.cursors.DictCursor) 方法创建一个可以执行SQL语句并且将结果作为字典返回的游标                        
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        
        # 使用 execute()  方法执行 SQL 查询 
        # format_map 格式化字符串拼接SQL参数
        cursor.execute(SQL_EXAMIN_REPORT.format_map({"agency_id": agency_id, "examin_date": examin_date}))
        # 使用 fetchall() 方法获取所有数据
        data = cursor.fetchall()
        
        # 关闭游标
        cursor.close()
        # 关闭数据库连接
        conn.close()
    	
        return data
      
    # SQL
    SQL_EXAMIN_REPORT = '''SELECT
        ther.id,
    FROM
        t_health_examin_record
    WHERE
        agency_id = '{agency_id}' AND examin_date = '{examin_date} 00:00:00'
    '''
    
posted @ 2021-05-26 17:31  背包の技术  阅读(229)  评论(0编辑  收藏  举报