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("数据生成完毕")
相关推荐
达梦产品与服务1 小时前
SQLark V4.4 更新 | 新增 SQL Server 数据库支持、自定义格式复制、Agent 辅助建表等 20+ 项功能已上线!
数据库
小Ti客栈3 小时前
MySQL 常用函数速查(完整篇)
数据库·mysql·adb
TomEval3 小时前
【测AI】第26篇:线上模型监控与告警体系 — 测试不是终点
人工智能·python·功能测试·ai
隔窗听雨眠3 小时前
高可用不止于数据库的全栈工程实践
数据库·架构设计·高可用
prince_zxill4 小时前
PEP 751 pylock.toml 实测:pip 26.3 装 6 个包版本全钉死,但 [web] 选不中任何东西
python·pip·依赖管理·pep 751
Thanks_ks6 小时前
Python 的垃圾回收——引用计数撑起日常,分代回收收拾残局
python·内存管理·垃圾回收·循环引用·引用计数·gc 模块·weakref
CyrusYiVPP6 小时前
实测 uv 0.13.7:同一套包,pip 装 94 秒,它只用 19 秒
人工智能·python
nice_lcj5206 小时前
MySQL 主从复制与读写分离:从库怎么跟着主库走
数据库·mysql·面试·binlog·读写分离·主从复制
yiangL_6 小时前
Python 学习笔记:递归、turtle绘图、字符串与函数
笔记·python·学习