1.环境准备
pip3 install pymysql
pip3 install sqlalchemy
2.连接数据库
import pymysql import numpy as np import pandas as pd from sqlalchemy import create_engine engine=create_engine(‘mysql+pymysql://root:123456@localhost:3306/demo‘) tables = pd.read_sql_query(‘show tables;‘, engine) tables=tables.rename(columns={‘Tables_in_datacenter‘:‘tbs‘}) def datas(sql): return pd.read_sql_query(sql, engine) def excute_sql(sql): conn = pymysql.connect(host="localhost",user="root",password="123456",database="datacenter",charset="utf8") cst = conn.cursor() cst.execute(sql)
conn.close()
然后可以如操作df一般去操作基本数据
tables.rename是对列进行重命名,因为默认的结果列名太长
excute_sql用于执行数据库的增删改操作