我们正在制作一款基于文字的游戏(MUD),并且遇到了这个障碍。
代码:
class RoomMove():
def __init__(self):
self.room = 1
self.name = 'Lorinth'
self.moveRooms()
self.updateRoom()
[额外代码无所谓]
def updateRoom(self):
global c
room = str(self.room)
room = (room)
print room
while room > 0:
c.execute("""SELECT * FROM RoomPlayers where ID=?""", room)
spaceCheck = c.fetchone()
print spaceCheck
counter = 1
if spaceCheck[counter] not in ('', None):
counter += 1
else:
room = self.room
name = self.name
c.execute("""UPDATE RoomPlayers SET '1'=? WHERE ID=?""", (name, room))
conn.commit()
它会抛出这个错误:
c.execute("""SELECT * FROM RoomPlayers where ID=?""", room)
ValueError: parameters are of unsupported type
编辑:我已经尝试了(房间)..但错误没有区别。
有什么想法吗?
谢谢!
答案 0 :(得分:1)
您可以阅读documentation:
fetchone()
获取查询结果集的下一行,返回单个序列,或者在没有更多数据可用时获取“无”。
如果没有更多数据,c.fetchone()会为spaceCheck变量分配None,因此当您尝试访问spaceCheck [counter]时会出现TypeError。
尝试类似的东西:
if spaceCheck is not None:
counter += 1
<强>更新强>
你应该替换
room = (room)
使用:
room = (room, )
另一次更新
假设您创建如下表格:
sqlite> CREATE TABLE RoomPlayers (ID numeric, player_name VARCHAR);
您的代码可能与此类似:
class RoomMove():
def __init__(self, room, name):
self.room = room
self.name = name
self.con = None
self.db_path = "./foo.sqlite"
def updateRoom(self):
try:
# Globals are evil. Don't use them
self.con = sqlite3.connect(self.db_path)
c = con.cursor()
# comparing tuple or string to number dosen't make sense. Compare original number
# You should check if room is valid inside constructor
# while room > 0 would probably lead to indefinite loop
if rooom > 0:
#You don't have to cast room number to string
c.execute("""SELECT id FROM RoomPlayers where ID=?""", (self.room, ))
spaceCheck = c.fetchone()
# Your counter takes only two values so you can do it like that
counter = 2 if spaceCheck is not None else 1
if counter == 1:
# Don't name columns '1' - it is really bad idea
# Like above - coneverting room and name to string is pointlees
c.execute("""UPDATE RoomPlayers SET 'player_name'=? WHERE ID=?""", (self.name, self.room))
self.con.commit()
finally:
# No matter what happens close connection
if self.con is not None:
self.con.close()
答案 1 :(得分:0)
解决上述问题的原因是什么:
sqlite3不读取整数,只读取字符串。 (实际上并非如此)
所以我将整数作为else循环中的字符串读取。
这里:
else:
room = self.room
name = self.name
c.execute("""UPDATE RoomPlayers SET '1'=? WHERE ID=?""", (name, room))
房间正在作为整数传递给c.execute,解决方案?
else:
room = str(self.room)
....
永远看到了!