美文网首页
python向数据库插入数据

python向数据库插入数据

作者: 叶叶阿姨 | 来源:发表于2020-01-09 15:58 被阅读0次

同事那要的代码 还没有自己用过 所以没有什么心得 自己看看吧

import pymysql
import random
import datetime


def randomtimes(start, end, n, frmt="%Y-%m-%d"):
    stime = datetime.datetime.strptime(start, frmt)
    etime = datetime.datetime.strptime(end, frmt)
    return [random.random() * (etime - stime) + stime for _ in range(n)]


# 打开数据库连接
db = pymysql.connect("数据库链接", "root", "密码", "被插入的表名")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT * from quick_poll_alerts")
res = cursor.fetchall()
temp_num = 0
while True:
    temp_num += 1
    temp = random.choice(res)
    sql = """INSERT INTO quick_poll_alerts(alerts_content, alerts_abstract, alerts_cover_photo,
    article_id, author_id, niche_id, regional_id, total_views, source_id, alerts_releasetime, alerts_title)
    values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s )"""
    sql2 = (temp[1], temp[2], temp[3], random.choice([3, 4, 5, 6, 11, 12]),
            random.choice([1, 2, 3, 4, 5]),
            random.choice([1, 4, 5, 6, 7]),
            random.choice([5, 6, 7, 8, 9]),
            random.randint(1, 200),
            temp[10],
            randomtimes('2012-01-01', '2020-01-05', 1)[0],
            temp[12])
    cursor.execute(sql, sql2)
    db.commit()
    print(temp_num)
    if temp_num == 1000000:
        break

db.close()

相关文章

网友评论

      本文标题:python向数据库插入数据

      本文链接:https://www.haomeiwen.com/subject/gawyactx.html