python · SQL | MySQL 配置与 python 连接数据库


来存档一下搞 sql 的过程,方便以后查阅。

  1. 安装与配置 mysql server:https://blog.csdn.net/zhende_lan/article/details/129318514
  2. 在同一个网页下载 mysql workbench(数据库可视化);
  3. 打开 workbench,新建一些表,用来测试:https://zhuanlan.zhihu.com/p/260139380
  4. python 连接 sql 的代码:
# pip install pymysql
import pymysql
import pandas as pd
def connect_db(host, user, password, database):
connect = pymysql.connect(host=host, user=user, password=password, database=database)
print("connect " + "success!" if connect else "failed!")
return connect
def get_all_data(cursor, table_name):
cursor.execute("select * from " + table_name)
results = cursor.fetchall()
description = cursor.description
# table head
df = pd.DataFrame(data=results, columns=[item[0] for item in description])
return df
if __name__ == '__main__':
# 连接数据库
conn = connect_db(host='localhost', user='root', password='123123', database='sys')
df = get_all_data(conn.cursor(), table_name='my_device')
# 保存 excel
df.to_excel('./get_db_data.xls', sheet_name='sheet1', index=False)
print('successfully save excel!')


本文作者:MoonOut

本文链接:https://www.cnblogs.com/moonout/p/17649417.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   MoonOut  阅读(51)  评论(0编辑  收藏  举报
历史上的今天:
2022-08-22 线性代数 | Jordan 标准型的笔记
2022-08-22 线性代数 | 三个二次型题目
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 Sibelius: Violin Concerto in D Minor, Op. 47:III. Allegro, ma non tanto Jascha Heifetz / Chicago Symphony Orchestra
Sibelius: Violin Concerto in D Minor, Op. 47:III. Allegro, ma non tanto - Jascha Heifetz / Chicago Symphony Orchestra
00:00 / 00:00
An audio error has occurred.