用python在后端将数据写入到数据库并读取

时间:2023-03-09 16:47:59
用python在后端将数据写入到数据库并读取

用python在后端将数据写入到数据库:

# coding:utf-
import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:, 端口:,数据库:mydb
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/python1')
import numpy as np
import datetime
start = datetime.datetime.now().strftime('%Y-%m-%d')
end = (datetime.datetime.now()+datetime.timedelta(days=)).strftime('%Y-%m-%d')
# 新建pandas中的DataFrame, 只有id,num两列
df = pd.DataFrame(data=np.random.randint(-,,(,)),index=pd.date_range('2018-1-1',periods=,dtype='datetime64[ns]', freq='D'),columns=None,dtype=int)
print(df.shape)
# 将新建的DataFrame储存为MySQL中的数据表,不储存index列
df.to_sql('data', engine, if_exists='append',index= True)

读取:

# -*- coding: utf- -*-

# 导入必要模块
import pandas as pd
from sqlalchemy import create_engine # 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:, 端口:,数据库:mydb
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/python1') # 查询语句,选出employee表中的所有数据
sql = '''
select * from student;
''' # read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql, engine)
# 输出employee表的查询结果
print(df.shape)