我认为我有正确的想法来做这个功能,但我不知道为什么我会这样做 我测试时出现此错误。有人可以帮我解决这个问题吗?
cur.execute(q)
sqlite3.ProgrammingError:提供的绑定数量不正确。该 当前语句使用1,并且提供了0。
当前尝试
def find_dept_courses(db, dept):
'''Return the courses from the given department. Use the "LIKE"
clause in your SQL query for the course name.'''
return run_query(db, '''SELECT DISTINCT Course FROM Courses WHERE
Course LIKE (? + 'dept%')''')
期望的输出
find_dept_courses('exams.db', 'BIO')
# [('BIOA01H3F',), ('BIOA11H3F',), ('BIOB10H3F',), ('BIOB33H3F',),
# ('BIOB34H3F',), ('BIOB50H3F',), ('BIOC12H3F',), ('BIOC15H3F',),
# ('BIOC19H3F',), ('BIOC32H3F',), ('BIOC37H3F',), ('BIOC50H3F',),
# ('BIOC58H3F',), ('BIOC59H3F',), ('BIOC61H3F',), ('BIOC63H3F',),
# ('BIOD21H3F',), ('BIOD22H3F',), ('BIOD23H3F',), ('BIOD26H3F',),
# ('BIOD33H3F',), ('BIOD48H3F',), ('BIOD65H3F',)]
查询功能:
def run_query(db, q, args=None):
"""(str, str, tuple) -> list of tuple
Return the results of running query q with arguments args on
database db."""
conn = sqlite3.connect(db)
cur = conn.cursor()
# execute the query with the given args passed
# if args is None, we have only a query
if args is None:
cur.execute(q)
else:
cur.execute(q, args)
results = cur.fetchall()
cur.close()
conn.close()
return results
答案 0 :(得分:0)
目前,您使用的是占位符,但未传递任何参数。其次,您将占位符?
与LIKE
表达式中的数据值连接起来。
只需将查询语句和数据值分开,然后单独留下?
:
def find_dept_courses(db, dept):
sql = '''SELECT DISTINCT Course FROM Courses WHERE Course LIKE ?'''
return run_query(db, sql, args=(dept+'%',))
答案 1 :(得分:0)
使用.execute
时,您需要将参数作为列表或元组传递,这里是示例
# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))
答案 2 :(得分:-1)
删除?并解析你的sql语法,所以dept被视为一个变量,例如sql应该评估为
SELECT DISTINCT课程FROM课程WHERE 课程喜欢'mydept%'
请注意,您可能容易使用此方法进行sql注入,而dept来自用户输入