Python写入本地数据库与excel表参考模板(根据情况进行调整)

PYTHON写入本地数据库与excel表

利用Python代码写入本地excel与sql数据库

1.生成数据&建表

先创建一张orders表,用于存放数据。

sql 复制代码
# 创建一个名为 orders 的表
# 如果这个表已经存在,那么就什么都不做
# 否则,创建一个名为 orders 的表
# 这个表有9个字段
# id 字段是表的主键
# orderid 字段存储订单的id
# price 字段存储订单的价格
# amount 字段存储订单的金额
# create_time 字段存储订单的创建时间
# payment_time 字段存储订单的支付时间
# delivery_time 字段存储订单的发货时间
# name 字段存储订单的收货人
# address 字段存储订单的收货地址
# phone 字段存储订单的收货人电话
create table if not exists test.orders
(
    id            int auto_increment primary key,
    orderid       double   null,
    price         double   null,
    amount        double   null,
    create_time   datetime null,
    payment_time  datetime null,
    delivery_time datetime null,
    name          text     null,
    address       text     null,
    phone         double   null
);

2.写入数据库或者excel表

python 复制代码
import pandas as pd
import numpy as np
import datetime 
import random
from sqlalchemy import create_engine

# 创建一个到mysql的连接引擎
# mysql+pymysql是指使用pymysql模块来连接mysql
# root是数据库的用户名
# xxxxxx是数据库的密码
# localhost是数据库的主机
# 3306是数据库的端口
# xxx是数据库的名称
# charset=utf8是指以utf8的编码来连接数据库
sql_conn=create_engine('mysql+pymysql://root:xxxxxx@localhost:3306/xxxx?charset=utf8')



def get_data(row):
    """
    生成row行订单数据
    每行数据包括
        orderid: 11位随机数
        price: 10-1000之间的随机浮点数
        amount: 1-price之间的随机浮点数
        create_time:现在的日期减去1-30天
        payment_time: create_time加上1-3天
        deliverty_time: payment_time加上1-7天
        name:随机的中国人姓名
        address:随机的中国省份和城市
        phone: 139开头的随机8位数
    """
    data_list=[]
    for i in range(1,row+1):
        order_id=str(random.randint(1,9))+"".join(str(random.randint(0,9)) for i in range(10))
        price=round(random.uniform(10,1000),2)
        amount=round(random.uniform(1,price),2)
        create_time=datetime.datetime.now()-datetime.timedelta(days=np.random.randint(1,30))
        payment_time=create_time+datetime.timedelta(days=np.random.randint(1,3))
        deliverty_time=payment_time+datetime.timedelta(days=np.random.randint(1,7))
        First_name=np.random.choice(['',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '])
        lastname=np.random.choice([' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '])
        First_name=np.random.choice(['王', '李', '张', '刘', '陈', '杨', '黄', '吴', '赵', '周', '徐', '孙', '马', '朱', '胡', '林', '郭', '何', '高', '罗'])
        lastname=np.random.choice(['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '峰', '宇', '超', '秀兰', '霞', '平', '刚', '桂英'])
        name=First_name+lastname
        province=np.random.choice([' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '])
        city = np.random.choice([' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '])
        address=province+city+np.random.choice([' ',' ',' ',' '])+str(np.random.randint(1,100))+' '
        province=np.random.choice(['北京市', '上海市', '广东省', '浙江省', '江苏省', '湖南省', '湖北省', '河南省', '山东省', '辽宁省', '吉林省', '黑龙江省'])
        city = np.random.choice(['北京市', '上海市', '广州市', '深圳市', '杭州市', '南京市', '武汉市', '长沙市', '郑州市', '济南市', '沈阳市', '哈尔滨市'])
        address=province+city+np.random.choice(['东区','西区','北区','南区'])+str(np.random.randint(1,100))+'号'
        phone='139'+''.join(str(np.random.randint(0,10)) for i in range(8))
        data_list.append([order_id,price,amount,create_time,payment_time,deliverty_time,name,address,phone])
        print(f"第{i}条数据已生成")
    return data_list

    
# 1. 调用get_data()函数,生成1000行订单数据,并将其存在data_list中
# 2. 将data_list转换为pandas DataFrame对象
# 3. 将DataFrame的列名设置为['orderid', 'price', 'amount', 'create_time', 'payment_time', 'delivery_time', 'name', 'address', 'phone']
# 4. 将数据写入到mysql数据库的orders表中
# 5. 如果orders表已经存在,则将其删除后重新创建
# 6. 将数据写入到excel文件中
# 7. 打印"数据生成完毕"
data_list=get_data(1000)
df=pd.DataFrame(data=data_list)
df.columns=['orderid', 'price', 'amount', 'create_time', 'payment_time', 'delivery_time', 'name', 'address', 'phone']
#生成到Mysql
df.to_sql('orders', con=sql_conn, if_exists='replace', index=False)
#生成到excela
# df.to_excel("orders.xlsx",index=False)
print("数据生成完毕")
相关推荐
IvorySQL1 小时前
PostgreSQL 技术日报 (3月11日)|4库合一性能提升350倍与内核新讨论
数据库·postgresql·开源
IvorySQL1 小时前
谁动了我的查询结果?PostgreSQL 联表加锁的隐藏陷阱
数据库·postgresql·开源
会员源码网3 小时前
Python中生成器函数与普通函数的区别
python
Java水解3 小时前
Python开发从入门到精通:Web框架Django实战
后端·python
爱可生开源社区4 小时前
🧪 你的大模型实验室开张啦!亲手测出最懂你 SQL 的 AI
数据库·sql·llm
曲幽5 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
赵渝强老师8 小时前
【赵渝强老师】使用TiSpark在Spark中访问TiDB
数据库·mysql·tidb·国产数据库
Lupino8 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
Qinana9 小时前
第一次用向量数据库!手搓《天龙八部》RAG助手,让AI真正“懂”你
前端·数据库·后端
Flittly9 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent