PyMySQL库安装

2019-12-22  本文已影响0人  wangyu2488

PyMySQL遵循Python DB-API2规范

2019年12月10日

https://pypi.org/project/PyMySQL/

安装

python3 -m pip install PyMySQL (多试几次 有时候网络问题会报错)


image.png

一般用法

import pymysql
# 1. 建立数据库连接
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='wy123456',
                             database='testdb',
                             charset='utf8')
try:
    # 2. 创建游标对象
    with connection.cursor() as cursor:
        # 3. 执行SQL操作
        # sql = 'select name, userid from user where userid >%s'
        # cursor.execute(sql, [0])
        sql = 'select name, userid from user where userid >%(id)s'
        cursor.execute(sql, {'id': 0})
        # 4. 提取结果集
        result_set = cursor.fetchall()
        for row in result_set:
            print('id:{0} - name:{1}'.format(row[1], row[0]))
    # with代码块结束 5. 关闭游标
finally:
    # 6. 关闭数据连接
    connection.close()

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

上一篇 下一篇

猜你喜欢

热点阅读