python安装PyMySQL

1确定Python版本 和 scripts目录下有pip.exe


运行- cmd (管理员) -  进入后输入: python  确定版本

python安装PyMySQL_第1张图片

指定到python下scripts目录下,然后输入 pip 确认 是否已安装 pip,(一般是已经安装的)

python安装PyMySQL_第2张图片


2pip安装 PyMySQL


python安装PyMySQL_第3张图片


3案例:

连接数据库并执行查询

import datetime
import pymysql.cursors

# 连接配置信息
config = {
    'host': '127.0.0.1', #本地服务器
    'port': 3306,
    'user': 'root',
    'password': '',
    'db': 'viomall',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor,
}
# 创建连接
connection = pymysql.connect(**config)

# 执行sql语句
try:
    with connection.cursor() as cursor:
        # 执行sql语句,进行查询
        sql = 'SELECT * FROM viomall.user_ebay'
        cursor.execute(sql)
        # 获取查询结果
        result = cursor.fetchall() #获取全部结果,取一条为 fetchone()
        print(result)
    # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
    connection.commit()

finally:
    connection.close();

执行结果为:表里有2条记录

[{'ebay_user_id': 10007, 'user_id': 10024}, {'ebay_user_id': 10046, 'user_id': 10163}]


你可能感兴趣的:(工作相关)