山东大学项目实训-灵思考评-与知识点查找的数据库操作(一)

        生成题目的原材料来自我们收集的知识点库,所以在生成题目的时候要先根据题目到数据库搜索到对应的知识点部分。

        根据指定的id从数据库表relationship中查询对应的记录

def select_id(id):
    # 连接数据库
    conn = pymysql.connect(
        host=host,
        user=user,
        password=password,
        database=database,
        charset=charset,
        autocommit=True,  # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
    )
    cursor= conn.cursor()
    sql="select * from relationship where id='"+ str(id) + "'"
    try:
        cursor.execute(sql)
        data = cursor.fetchone()
        
    except Exception as e:
            print("发生异常",Exception)
            print(e.args)
            print("\n")
            print(traceback.format_exc())
    cursor.close()
    conn.close()
    return data
  1. 数据库连接

    • 使用pymysql库建立与MySQL数据库的连接。
    • 连接参数(hostuserpassword等)需在外部定义。
    • autocommit=True表示自动提交事务(无需手动调用conn.commit())。
  2. SQL查询

    • 直接拼接SQL语句:"select * from relationship where id='" + str(id) + "'"
    • 注意:这种方式存在SQL注入风险(如果id来自用户输入)。
  3. 结果获取

    • cursor.fetchone():返回查询结果的第一行(单条记录)。
    • 如果查询无结果,返回None
  4. 异常处理

    • 捕获所有异常(Exception),并打印:
      • 异常类名(Exception)。
      • 异常参数(e.args)。
      • 完整堆栈跟踪(traceback.format_exc())。

下面是搜索与输入相关的知识点的函数。

def find_entity(text,type,equal):
    data_list = []
    # 连接数据库
    conn = pymysql.connect(
        host=host,
        user=user,
        password=password,
        database=database,
        charset=charset,
        autocommit=True,  # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
    )
    cursor= conn.cursor()
    if type == 1:
        if equal:
            sql = "select * from relationship where entity1='" +text + "'"
        else:
            sql = "select * from relationship where entity1 like  '%" +text +"%' "
    elif type == 2:
        if equal:
            sql = "select * from relationship where entity2='" +text + "'"
        else:
            sql = "select * from relationship where entity2 like  '%" +text +"%' "
    try:
        cursor.execute(sql)
        data_list = cursor.fetchall()
        
    except Exception as e:
            print("发生异常",Exception)
            print(traceback.format_exc())

     
    cursor.close()
    conn.close()
    return data_list

使用pymysql,定义了一个 find_entity() 函数,用于从数据库中查询与指定实体相关的数据,

使用配置的主机、用户名、密码,连接数据库,支持两种查询方式,

  • 精确匹配(equal=True
    • 生成 SQL:SELECT * FROM relationship WHERE entityX = '输入文本'
  • 模糊匹配(equal=False
    • 生成 SQL:SELECT * FROM relationship WHERE entityX LIKE '%输入文本%'

实现对用户输入关键词的不同程度的匹配。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值