生成题目的原材料来自我们收集的知识点库,所以在生成题目的时候要先根据题目到数据库搜索到对应的知识点部分。
根据指定的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
-
数据库连接:
- 使用
pymysql
库建立与MySQL数据库的连接。 - 连接参数(
host
、user
、password
等)需在外部定义。 autocommit=True
表示自动提交事务(无需手动调用conn.commit()
)。
- 使用
-
SQL查询:
- 直接拼接SQL语句:
"select * from relationship where id='" + str(id) + "'"
。 - 注意:这种方式存在SQL注入风险(如果
id
来自用户输入)。
- 直接拼接SQL语句:
-
结果获取:
cursor.fetchone()
:返回查询结果的第一行(单条记录)。- 如果查询无结果,返回
None
。
-
异常处理:
- 捕获所有异常(
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 = '输入文本'
- 生成 SQL:
- 模糊匹配(
equal=False
):- 生成 SQL:
SELECT * FROM relationship WHERE entityX LIKE '%输入文本%'
- 生成 SQL:
实现对用户输入关键词的不同程度的匹配。