利用Python代向像数据库中添加多天数据(主要用来造数据)

def insertData(db,cursor,tablename,*key,**kwargs):
    # *key返回的是元组(),**返回的是字典
    values = []
    for value in kwargs.values():
        values.append(value)
    print(tuple(values))
    sql = 'insert into {} {}'.format(tablename,key).replace("'","")+' VALUES {}'.format(tuple(values))
    print(sql)
    try:
        cursor.execute(sql)
        db.commit()
        print("成功添加数据")
        print("插入数据的ID:",cursor.lastrowid)
    except Exception as e:
        print(e)
        # 发生错误时候回滚
        db.rollback()
db = config.db
cur = db.cursor(cursor=cursors.DictCursor)
for i in range(0,99):
     name = 'wangquntest_'.join(random.sample(string.ascii_letters+string.digits+string.punctuation,3))
     age =random.randint(20,99)
     insertData(db,cur,"ty_test_info","name","age",name = name,age = age)

 

posted @ 2020-02-25 11:54  天空是我喜欢的颜色  阅读(258)  评论(0编辑  收藏  举报