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

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

1.生成数据&建表

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

# 创建一个名为 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表

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("数据生成完毕")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值