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("数据生成完毕")
相关推荐
倔强青铜三8 分钟前
苦练Python第23天:元组秘籍与妙用
人工智能·python·面试
apihz10 分钟前
域名WHOIS信息查询免费API使用指南
android·开发语言·数据库·网络协议·tcp/ip
gwcgwcjava16 分钟前
[时序数据库-iotdb]时序数据库iotdb的安装部署
数据库·时序数据库·iotdb
SHUIPING_YANG30 分钟前
根据用户id自动切换表查询
java·服务器·数据库
Norvyn_732 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
爱吃烤鸡翅的酸菜鱼42 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
超奇电子1 小时前
阿里云OSS预签名URL上传与临时凭证上传的技术对比分析
数据库·阿里云·云计算
chao_7891 小时前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
神仙别闹1 小时前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
m0_653031361 小时前
PostgreSQL技术大讲堂 - 第97讲:PG数据库编码和区域(locale)答疑解惑
数据库·postgresql