从数据库中读取内容WHERE'id'=

时间:2014-03-09 13:00:40

标签: python mysql

我正在尝试用Python构建一个检查(Dutch = overhoor)程序。这是我的代码:

cursor = cnx.cursor()

willekeurig = random.randint(0,9)

query = ('SELECT FRwoord, NLwoord FROM unite8app1 WHERE "id"=willekeurig')
cursor.execute(query)

for (NLwoord, FRwoord) in cursor:
    print("Wat is de vertaling van: " + FRwoord + "?")

vertaling = input()

if vertaling == NLwoord:
    print("Well done")
else:
    print("Helaas")

for (FRwoord, NLwoord) in cursor:
    print(FRwoord,NLwoord)
print(query)
cnx.close

我正在尝试根据我的数据库中该问题的ID获取一个随机问题。我尝试了一些替代方案:

WHERE 'id'=1
WHERE 'ID'=1 
etc

但是如果我运行我的程序(按下回车后)它不想工作它说没有定义NLwoord和FRwoord,但当我删除那段代码时它工作得很好。 (如果我的数据库中只有1个项目)

我的问题是如何从我的数据库中获取随机ID?我已经包含了一些数据库的图片。

http://updo.nl/file/37e39c15.JPG http://updo.nl/file/1de64d64.JPG

2 个答案:

答案 0 :(得分:1)

现在你没有传递willekeurig的价值,但文字willekeurig。尝试这两行代码进行查询&执行insted:

query = "SELECT FRwoord, NLwoord FROM unite8app1 WHERE id=%s"
cursor.execute(query, (willekeurig,))

答案 1 :(得分:0)

你是否尝试过没有id周围的引号?

你也应该能够使用:

SELECT FRwoord, NLwoord FROM unite8app1 ORDER BY RAND() LIMIT 1