【问题标题】:SELECT statement returning the column name instead of the VALUE (for that said column)SELECT 语句返回列名而不是 VALUE(对于该列)
【发布时间】:2022-03-07 10:11:02
【问题描述】:

我正在尝试使用两个列名“id”和“easy_high_score”将信息解析到 SELECT 语句中,这样我就可以在我的程序中操作它们的两个列的值,但是在尝试获取列的值时'easy_high_score',应该是一个像 46 或 20 这样的整数,它会返回一个字符串 ('easy_high_score',)。

即使表中没有提到 [('easy_high_score',)],它仍然会打印出来。在表中,id 1 具有我正在尝试获取的正确值和信息,但无济于事。我对 SQLite3 还很陌生。

if mode == "Easy":
    mode = 'easy_high_score'

if mode == "Normal":
    mode = "normal_high_score"

if mode == 'Hard':
    mode == "hard_high_score"


incrementor = 1 ##This is used in a for loop but not necessary for this post
c.execute("SELECT ? FROM players WHERE id=?", (mode, incrementor))
allPlayers = c.fetchall()
print(allPlayers)  #This is printing [('easy_high_score',)], when it should be printing an integer.

预期结果:20(或表示简单模式高分的整数)

实际结果:[('easy_high_score',)]

【问题讨论】:

  • 您不能对表名或列名使用参数。它们必须在编译时直接出现在语句中。
  • @Shawn 抱歉,我不确定你的意思。你能详细说明一下吗?

标签: python-3.x sqlite


【解决方案1】:

不能使用参数指定列名,它应该逐字出现在查询中。像这样修改执行查询的行:

c.execute("SELECT %s FROM players WHERE id=?" % mode, (incrementor,))

【讨论】:

    【解决方案2】:

    造成这种情况的一个可能原因是双引号与单引号。

    'SELECT "COLUMN_NAME" FROM TABLE_NAME' # will give values as desired
    "SELECT 'COLUMN_NAME' FROM TABLE_NAME" # will give column name like what you got
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      相关资源
      最近更新 更多