Sqlite更新不能正常工作python

2024-05-06 09:40:55 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:经过一些测试,我发现失败的不是addpoint方法。

我在为一个irc机器人做一个小游戏。此方法将更新数据库中名为“score”的分数,只有两个玩家。这是一个sqlite数据库。主要是更新sql不能正常工作。

谢谢

def addpointo(phenny, id, msg, dude):
 try:
  for row in c.execute("select score from score where id = '0'"):
   for bow in c.execute("select score from score where id = '1'"):
    if int(row[0]) == 3:
     phenny.say("Winner is " + dude)
     clear("score") # clear db
     clear("sap") # clear db
    elif int(bow[0]) == 3:
     phenny.say("Winner is " + dude)
     clear("score") # clear db
     clear("sap") # clear db
    else:
     phenny.say(msg)
     s = c.execute("select score from score where id=?", id)
     a = int(s.fetchone()[0]) + 1
     print a
     c.execute("update score SET score =? where id =?", (a, id)) #here i got some prolem
     conn.commit()
 except Exception:
  phenny.say("Error in score. Try to run '.sap clear-score' and/or '.sap clear-sap'")
  pass

这就是我创建score db的方法

def createscore():
 if not (checkdb("score") is True):
  c.execute('''create table score (id int, score int)''')
  c.execute('insert into score values (0, 0)')
  conn.commit()
  c.execute('insert into score values (1, 0)')
  conn.commit()

错误消息:参数的类型不受支持


Tags: 方法infromidexecutedbwhereselect
3条回答

假设“c”是一个游标,则代码还有一个严重问题。SQLite游标一次获得一个结果行(即每次通过for循环),而不是提前获得所有结果行。如果重用游标,则它将用新的查询替换当前查询。例如,此代码只在循环中运行一次:

for row in c.execute("select * from score"):
   for dummy in c.execute("select 3"):
      print row, dummy

您的解决方案包括:

  • 在结尾处添加.fetchall():c.execute(“select*from score”).fetchall(),它一次获取前面的所有行,而不是一行。

  • 使用不同的光标,这样每个光标之间的迭代不会影响其他光标

  • 创建一个新的游标-将c.execute(“…”)替换为conn.cursor().execute(“…”) pysqlite的最新版本允许您执行conn.execute(“…”),这实际上是在幕后执行上述操作。

光标是非常便宜的,所以不要试图保存它们-使用尽可能多-你不会有这样的错误。

一般来说,非常小心地重用迭代器和修改在同一系列循环中迭代的内容也是一个好主意。不同的类以不同的方式表现,所以最好假设它们不喜欢它,除非另有说明。

上次选择时出错

这个

s = c.execute("select score from score where id='id'")

必须写成

s = c.execute("select score from score where id=?", id)

虽然最初的作者很可能已经离开了,但我想我会在这里留下一个答案给未来的谷歌用户(比如我)。

我想这里发生的是下面的错误。。。

ValueError: parameters are of unsupported type

。。。实际上是来自下面的一行(与作者所说的相反)。

s = c.execute("select score from score where id=?", id)

这里的问题是Cursor.execute接受查询字符串作为第一个参数(他有权这样做),但是listtuple,或者dict作为第二个参数。在这种情况下,他需要将这个id包装成元组或列表,如下所示:

s = c.execute("select score from score where id=?", (id,))

列表或元组可以与位置参数一起使用(当您使用问号?作为占位符时)。还可以对命名参数使用dict:key,如下所示:

s = c.execute("select score from score where id=:id", {"id": id})

相关问题 更多 >