Python SQLite中的语法错误
下面的代码是更新过的,可以正常工作的代码
我在运行这个代码的时候遇到了语法错误。这里是相关的代码:
import sqlite3
mydatabase="/Users/noahclark/cities.db"
connection=sqlite3.connect(mydatabase)
cur = connection.cursor()
def getDaysURLS(self):
day = cur.execute('select state from cities where city = "pointer"')
day = cur.fetchone()[0]
print day
cur.execute('select URL from cities where day = ?', (str(day),))
当我运行这段代码时,出现了以下错误。
Tkinter.py", line 1410, in __call__
return self.func(*args)
File "tkinter.py", line 50, in getDaysURLS
cur.execute(urlstring)
OperationalError: near "<": syntax error
我可以在sqlite命令行中运行 -- 从城市中选择州,条件是城市是"pointer" -- 这一行,它是可以正常工作的。
有没有什么建议或者提示?提前谢谢大家。
3 个回答
1
不要使用双引号。SQLite用双引号来处理一些特殊的名字,比如字段名和表名。应该使用单引号。另外,你应该用 =
而不是 is
:
day = cur.execute("select state from cities where city = 'pointer'")
更新: cur.execute()
返回的是游标 cur
,而不是查询的结果。你需要调用 cursor.fetchone()
来获取值:
# Execute the query. If all went well, you can use the cursor to navigate through
# the results.
cur.execute("select state from cities where city = 'pointer'")
# Fetch the next row and extract the first value in the row.
day = cur.fetchone()[0]
3
SQLite遵循SQL的标准:字符串要用单引号括起来,而不是双引号。此外,通常用=来检查字符串是否相等。
1
在SQL中,只有在检查空值时才使用is
day = cur.execute('select state from cities where city = "pointer"')
或者更好的做法是:
day = cur.execute('select state from cities where city = ?',("pointer",))
编辑
urlstring = "select URL from cities where day is" + str(day)
cur.execute(urlstring)
- 使用我之前展示的?方法
- 在is后面需要留一个空格
- cur.execute()不会像那样返回值。我不太确定它返回什么。你需要使用一个获取值的方法。