当前位置: 首页 > article >正文

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

PYTHON写入本地数据库与excel表

  • 利用Python代码写入本地excel与sql数据库
    • 1.生成数据&建表
    • 2.写入数据库或者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("数据生成完毕")

http://www.kler.cn/a/296993.html

相关文章:

  • 《JavaEE进阶》----13.<Spring Boot【配置文件】>
  • 大奖收割机!望繁信科技荣获年度技术创新和应用品牌奖
  • 移动硬盘无法访问怎么修复?
  • 拥抱 VSCode:你的前端开发利器!
  • 大模型微调训练营毕业总结
  • 【HarmonyOS】- HAR与HSP区别及使用原则
  • NLP从零开始------文本中阶处理之序列到序列模型(完整版)
  • 计算机专业选题推荐-基于python的岗位兼职招聘平台【python-爬虫-大数据定制】
  • liunx io模型多路复用
  • 果然,秋招会惩罚每一个本末倒置的应届生
  • 启动与登录Mysql
  • JS_对象的创建
  • 防近视护眼台灯什么牌子好?五款防近视效果好的护眼台灯推荐
  • 春日美食家:SpringBoot网上订餐系统
  • 使用PowerShell连接国际版Exchange Online合规保护
  • Vue3 动态组件
  • LeetCode 热题 100 回顾
  • c#中Graphics常用的属性
  • 十二、C语言:内存函数
  • matlab数据批量保存为excel,文件名,行和列的名称设置