尝试在python中运行sql查询时出错

bnlyeluc  于 2023-03-28  发布在  Python
关注(0)|答案(1)|浏览(210)

我已经用pyodbc.connect()连接到我的access数据库,但是当我试图运行一个查询时,我得到了这个错误消息,但是我看不到代码中的错误。我正在运行一个基于用户输入的查询,所以我实现了嵌套的if语句来运行一个基于用户输入的查询。下面是我的代码

cursor = conn.cursor()
  # Runs a different query depending on the course and year
  if year == "Nat 5":
    if course == "SDD":
      sql = ('SELECT question, correct_answer FROM question_data WHERE question_type = SDD AND year_group = Nat 5')
    elif course == "CS":
      sql = ('SELECT question, correct_answer FROM question_data WHERE question_type = CS AND year_group = Nat 5')
    elif course == "WDD":
      sql = ('SELECT question, correct_answer FROM question_data WHERE question_type = WDD AND year_group = Nat 5')

  if year == "Higher":
    if course == "SDD":
      sql = ('SELECT question, correct_answer FROM question_data WHERE question_type = SDD AND year_group = Higher')
    elif course == "CS":
      sql = ('SELECT question, correct_answer FROM question_data WHERE question_type = CS AND year_group = Higher')
    elif course == "WDD":
      sql = ('SELECT question, correct_answer FROM question_data WHERE question_type = WDD AND year_group = Higher')

  cursor.execute(sql)
  rows = cursor.fetchall()

当我尝试运行它给我以下错误信息

TypeError: The first argument to execute must be a string or unicode query.

我想运行一个不同的查询取决于用户输入的程序中的早期,但似乎有一个错误,在我的实现查询的cursor.execute行.有人知道到底是什么问题?

  • 编辑

我用的是f字符串格式,现在有了这个格式

sql = (f'SELECT question, correct_answer FROM question_data WHERE question_type = {course} AND year_group = {year}')

但是,我现在得到以下错误消息

Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 3. (-3010) (SQLExecDirectW)')

我被告知错误消息指的是下面的代码行。

cursor.execute(sql)
6pp0gazn

6pp0gazn1#

考虑pyodbc和所有其他Python DB-API以及Python以外运行SQL查询的语言支持的参数化的最佳实践。此外,这样做可以避免许多ifelif需求。
具体来说,你的第一个错误可能是由于与你发布的不同的代码示例,其中sql不是标量字符串,而是元组或列表。请注意:cursor.execute的第二个参数通常需要一个元组、列表或其他可迭代对象。后一个错误是由于SQL语句中格式化的Python变量缺少引号。但是,参数避免了使用引号或连接SQL语句的需要。

cursor = conn.cursor()
# Runs a different query depending on the course and year
sql = (
    'SELECT question, correct_answer '
    'FROM question_data '
    'WHERE question_type = ? AND year_group = ?'
)

cursor.execute(sql, [course, year])
rows = cursor.fetchall()

相关问题