import pandas as pd
import pymysql
from sqlalchemy import create_engine
# 初始化数据库连接,MySQL的用户为root, 密码为test123, 端口为3306,数据库为test_db
#engine=create_engine('mysql+pymysql://root:test123@localhost:3306/test_db')
#数据库为:192_168_28_31,查询的数据表:wp_users
engine=create_engine('mysql+pymysql://root:35493@127.0.0.1:3306/192_168_28_31')
# 查询表 basic_info 中的所有数据
sql = 'select * from wp_users;'
df = pd.read_sql_query(sql, engine)
print(df)
'''
===================== RESTART: C:/Users/czliu/Desktop/t.py =====================
ID user_login ... user_status display_name
0 1 liutz ... 0 liutz
1 4 smart ... 0 dolphin_smart
2 5 beer ... 0 敏
3 40 freemanmerritt ... 0 freemanmerritt
4 41 seanhines389 ... 0 seanhines389
5 42 kirbykraus06 ... 0 kirbykraus06
6 43 karlbrinson8 ... 0 karlbrinson8
7 44 etsukolajoie ... 0 etsukolajoie
8 45 albertalerma324 ... 0 albertalerma324
9 46 kittreacy841 ... 0 kittreacy841
10 47 andrametts24334 ... 0 andrametts24334
11 48 albert02a782221 ... 0 albert02a782221
12 49 magdakeating20 ... 0 magdakeating20
13 50 wyattaie818 ... 0 wyattaie818
[14 rows x 10 columns]
'''
#====写入数据====
# 新建一个 DataFrame
df1 = pd.DataFrame({'id':[123,785], 'name':['Liuyun','liutz']})
print(df1)
# 将新建的 DataFrame 储存到当前数据库的数据表 stu 中
df1.to_sql('stu', engine)
#将 excel 表中数据写入 MySQL 的新表中,例如对于如下 Excel 表:
只要接着执行如下代码:
df2 = pd.read_excel("stu_scores.xlsx")
df2.to_sql('scores', engine, index = False) # 不储存 index 列