Python实现将word的数据存入数据库

说明

在此记录如何将word里的题存入数据库

代码

import pymysql
import random
import docx

# 导入数据
path = 'test2.docx'
file = docx.Document(path)
# 连接数据库
db = pymysql.connect(host="localhost", user="root", password="123456", db="tiku", port=3306)
cur = db.cursor()

# word的段落
text = file.paragraphs
# word的段数
para = len(file.paragraphs)
# 要导入数据库的题数
times = int(para/6)
tag = 0

while True:
    while True:
        try:
            # 生成随机数
            num = random.randint(100000, 999999)
            # 生成sql语句 查询数据库里是否已存在相同的id
            sql = "select * from python_question where id = %d" % (num)
            cur.execute(sql)  # 执行sql语句
            results = cur.fetchall()  # 获取查询的所有记录
            if results:
                # id已存在,则跳过本次
                continue
            else:
                # 随机数不存在则作为Id
                question = text[tag*6+0].text # 题目
                A = text[tag*6+1].text  #选项
                B = text[tag*6+2].text
                C = text[tag*6+3].text
                D = text[tag*6+4].text
                answer = text[tag*6+5].text #答案选项
                tag = tag + 1
                sql_insert = "insert into python_question(question, A, B, C, D, id, answer) " \
                             "values ('%s', '%s', '%s', '%s', '%s', %d, '%c')" % (question, A, B, C, D, num, answer)
                try:
                    cur.execute(sql_insert)
                    # 提交'
                    db.commit()
                except Exception as e:
                    # 错误回滚
                    db.rollback()

        except Exception as e:
            raise e
        # 题目存完 退出循环
        if tag == times:
            break
        # 题目存完 退出循环
    if tag == times:
        break
# 程序完  关闭数据库
db.close()
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值