Python pymysql 模块

pymysql 是 Python3 连接 MySQL 的一个模块,常见用法如下:

[root@localhost ~]$ pip3 install pymysql    # 安装 pymysql 模块
In [1]: import pymysql

In [2]: conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456')    # connect()用于连接MySQL数据库,结果返回一个连接对象
                                                                                  # 常用的连接参数有:host 、user 、passwd 、db 、port
In [3]: cur = conn.cursor()               # 创建游标,用来存放执行SQL语句所检索出来的结果集

In [4]: cur.execute('show databases')     # 使用游标来执行SQL语句,8L表示结果有8行,结果会存存储在游标中
Out[4]: 8L

In [5]: cur.fetchone()
Out[5]: ('information_schema',)           # fetchone()用于查看一条结果

In [6]: cur.fetchmany(3)
Out[6]: (('mysql',), ('performance_schema',), ('test',))    # fetchmany()用于查看多条结果

In [7]: cur.fetchall()
Out[7]: (('test1',), ('test2',), ('test3',), ('wordpress',))    # fetchall()用于查看所有结果

In [8]: cur.close() # 关闭游标
In [9]: conn.close() # 关闭数据库连接

在 Python 中的写法:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import pymysql

def connectMySQL():
    db_config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'passwd': '123456',
        'db': 'mysql',
        'charset': 'utf8',
    }

    conn = pymysql.connect(**db_config)
    return conn

if __name__ == '__main__':
     conn = connectMySQL()
     cur = conn.cursor()
     try:
         cur.execute('show tables;')
         result = cur.fetchall()
         print(result)
         cur.close()
         conn.commit()             <--- 这里使用MySQL事务,如果执行SQL语句成功则提交,如果执行失败则回滚
     except:
         conn.rollback()
         print("执行SQL语句失败!")
     finally:
         conn.close()

使用 MySQL 连接池:

我们对数据库进行查询/插入/更新等操作,需要先连接数据库,创建数据库连接是一个很耗时的操作,为了避免多次连接 MySQL 数据库,我们可以使用 MySQL 连接池;
MySQL 连接池(Connection Pooling)是 MySQL 程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由 MySQL 程序动态地对池中的连接进行申请,使用,释放。

[root@localhost ~]$ pip3 install DBUtils    # 安装DBUtils
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import pymysql
from DBUtils.PooledDB import PooledDB

def connectMySQL():
    db_config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'game',
        'passwd': 'cqbygame',
        'db': 'mysql',
        'charset': 'utf8',
    }

    pool = PooledDB(pymysql, 5, **db_config)    # 创建连接池,指定创建5个数据库连接
    conn = pool.connection()                    # 以后每次需要连接数据库就用connect()函数获取连接
    return conn

if __name__ == '__main__':
     conn = connectMySQL()
     cur = conn.cursor()
     try:
         cur.execute('show tables;')
         result = cur.fetchall()
         print(result)
         cur.close()
         conn.commit()
     except:
         conn.rollback()
         print("执行SQL语句失败!")
     finally:
         conn.close()

    

    

原文地址:https://www.cnblogs.com/pzk7788/p/10447637.html