python操作mysql数据库(windows版)

一、环境准备

1、python下载以及环境变量配置

https://www.python.org/

 

2、conda下载以及环境变量配置

https://docs.conda.io/en/latest/miniconda.html

path中添加环境

D:\miniconda3
D:\miniconda3\Scripts

 

3、安装pymysql(pymssql)类库

 pip install pymysql

 如果遇到:WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

参考如下:

https://blog.csdn.net/qq_44845794/article/details/107554809

 

4、利用Python操作MySQL数据库

参考 https://www.cnblogs.com/wintest/p/12152687.html

import pymysql

def select_db(select_sql):
    """查询"""
    # 建立数据库连接
    db = pymysql.connect(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="admin_123",
        db="easyweb-security"
    )
    # 通过 cursor() 创建游标对象,并让查询结果以字典格式输出
    cur = db.cursor(cursor=pymysql.cursors.DictCursor)
    # 使用 execute() 执行sql
    cur.execute(select_sql)
    # 使用 fetchall() 获取所有查询结果
    data = cur.fetchall()
    # 关闭游标
    cur.close()
    # 关闭数据库连接
    db.close()
    return data

select_sql = 'SELECT * FROM qtc_product'
print(select_db(select_sql))

  

posted @ 2021-04-21 01:13  伐丶木累  阅读(283)  评论(0编辑  收藏  举报