- 新人python学习计划
- 一、txt文件列表数据增加前缀
- 1.解决方案
- 二、pycharm向数据库内批量写入测试数据
需求描述:当前有一个ID列表,例如
1414141414
1515151515
···
实际业务需要在每一行数据前增加前缀86,如
861414141414
861515151515
···
代码如下(示例):
target = open("C:/Users/HRjun/Desktop/目标文件.txt" , "w+")
with open("C:/Users/HRjun/Desktop/源文件.txt" , "r" , encoding="utf8") as f:
lines = f.readlines()
for i in lines:
str_lise = "86{}".format(i)
print(str_lise.strip())
target.write(str_lise)
# target.write("\n")
#open() 读取目标文件,参数“w+” 为读写模式,“r”为只读模式,write() 写入目标文件,自带换行,所以下方的“\n”没有必要
这就齐了,测试输入
1410829246946
1410829309841
1410829310574
输出
861410829246946
861410829309841
861410829310574
不聪明,但能用!
二、pycharm向数据库内批量写入测试数据python向MySQL数据库中写入数据,主要使用pymysql包
import pymysql
import random
import time
import datetime
# mysql包 / 随机数 / 两个时间相关的包
写入数据库相关信息
host、端口、库名、用户名、密码等
端口3306无须加 “ ”
conn = pymysql.connect(
host="xxxx" ,
port=3306,
database = "xxxx",
user="xxxx",
password="xxxx",
charset="utf8"
)
生成游标对象
cur = conn.cursor()
编写需执行的sql语句
sql_create = """
create table order_info(
order_id int primary key auto_increment ,
service_start_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ,
service_end_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ,
user_id bigint(20) ,
order_type varchar(16),
fee bigint(20),
status varchar(16)
)
"""
sql_insert = "insert into order_info(service_start_time , service_end_time , user_id , order_type , fee , status) values (%s , %s , %s , %s , %s , %s)"
sql_select = "select * " \
"from pcc_wx_user where " \
"datediff(create_time , '2022-1-1') between 0 and 30"
时间参数配置,用到了time包
a1 = (2022 , 4 , 19 , 0 , 0 , 0 , 0 , 0 , 0)
b1 = (2022 , 4 , 20 , 0 , 0 , 0 , 0 , 0 , 0)
a2 = (2022 , 4 , 19 ,23 , 59 , 59 , 0 , 0 , 0)
b2 = (2022 , 4 , 20 ,23 , 59 , 59 , 0 , 0 , 0)
start_1 = time.mktime(a1)
end_1 = time.mktime(a2)
start_2 = time.mktime(b1)
end_2 = time.mktime(b2)
order_type = [ "IOT_PACKAGE" , "NO_PAY" , "ACTIVITY" , "ENTERPRISE"]
#这里显得很蠢,后续有很大优化空间
通过循环向数据库写入测试数据
for i in range(1000):
random_user_id = random.randint(1,300)
random_fee = random.uniform(1,200)
random_type = random.randint(0,3)
t1 = random.randint(start_1, end_1)
t2 = random.randint(start_2, end_2)
date_touple_1 = time.localtime(t1)
date_touple_2 = time.localtime(t2)
date_1 = time.strftime("%Y-%m-%d %H:%M:%S", date_touple_1)
date_2 = time.strftime("%Y-%m-%d %H:%M:%S", date_touple_2)
cur.execute(sql_insert , (date_1 , date_2 , random_user_id ,order_type[random_type] , random_fee ,"SUCCESS" ))
#执行 sql 语句,execute(),执行select的话不需要第二个参数,直接就是
# cur.execute(sql_select)
conn.commit()
print("添加成功")
完后结束
cur.close()
conn.close()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)