标签:_id tin ids ftime com value menus cli cut
需求:
1.需要往数据库插入批量数据,且数据需要随机,带有日期格式的数据。
2.查看目的接收表,存在唯一key,字段2是日期格式。其他数据可以一样。
首先需要写一个链接数据库的函数:import MySQLdb
class MySql():
def __init__(self, db):
self.mysql = MySQLdb.Connect(
host="10.100.111.111",
port=33066,
user="mysql",
passwd="123456",
db=db,
charset="utf8")
self.cursor = self.mysql.cursor()
def quary(self, sql):
"""
查询
:param sql:
:return:
"""
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
def update(self, sql):
"""
修改
:param sql:
:return:
"""
self.cursor.execute(sql)
self.mysql.commit()
def delete(self, sql):
"""
删除
:param sql:
:return:
"""
self.cursor.execute(sql)
self.mysql.commit()
def insert(self, sql):
"""
插入
:param sql:
:return:
"""
self.cursor.execute(sql)
self.mysql.commit()
return "success"
def close(self):
self.mysql.close()
然后利用python循环写一个日期格式转化的函数:
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
else:
return json.JSONEncoder.default(self, obj)
def test1(self):
"""
id为唯一key,不能相同,需要查询到count总数得到id 时间是当前时间+1天生成sql语句
"""
ids = 174
cur_date = time.strftime("%Y-%m-%d")
start_time = datetime.strptime(cur_date, "%Y-%m-%d")
for i in range(50):
ids = ids + 1
dt = start_time + timedelta(days=i)
to_date = json.dumps(dt, cls=DateEncoder) # 将datetime格式转化为json格式
to_date = to_date[1:11] # 取string中的年月日
value = (
ids, to_date, ‘0104‘, ‘10‘, ‘1609725600‘, 64, ‘产品测试‘, 1100018191, ‘mytest‘,
‘5ff674f5e4b0fd510e457fd2‘, ‘1.7号啊‘,
0, ‘01‘, ‘06‘, ‘01‘, ‘0‘, ‘菜单2‘, ‘908E14881C52DF30A50C93491AE2BA8C‘, ‘1‘, ‘123‘, 10001, 9999, 912)
sql = """INSERT INTO ads_marketing_report.test_table(id, dt, fdate, ftime, servertime, agency_id, agency_name, owner_id, owner_name, service_id, service_name, service_platform, sbiztype, tritype, menulev, menuseq, btnele, btnlinkmd, functype, smssource, expose_nums, expose_uv, click_nums)
VALUES""" + str(value).decode(‘string_escape‘)
mysql.insert(sql=sql)
插入多少条 循环多少次就行,或者研究下存储过程插入也行的
标签:_id tin ids ftime com value menus cli cut
原文地址:https://www.cnblogs.com/testling/p/14262173.html