简体   繁体   English

Python SQLite中的语法错误

[英]Syntax Error In Python SQLite

THE CODE BELOW IS UPDATED CODE THAT WORKS 下面的代码有效的更新代码

I am getting a syntax error when I try to run this. 尝试运行此命令时遇到语法错误。 Here is the relevant code: 以下是相关代码:

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),))

When I run this code, I get the following error. 运行此代码时,出现以下错误。

  Tkinter.py", line 1410, in __call__
  return self.func(*args)
  File "tkinter.py", line 50, in getDaysURLS
  cur.execute(urlstring)
  OperationalError: near "<": syntax error

I can run the -- select state from cities where city is "pointer" -- line in the sqlite command line and it works. 我可以在sqlite命令行中运行-从城市是“指针”的城市中选择状态-行。

Any ideas or pointers? 有什么想法或建议吗? Thanks in advance. 提前致谢。

SQLite follows the SQL standard: strings are enclosed in single quotes, not double quotes. SQLite遵循SQL标准:字符串用单引号引起来,而不是双引号引起来。 Also, generally use = to check for string equality. 另外,通常使用=检查字符串是否相等。

Only use is in sql when checking for null 检查null时仅在sql中使用

  day = cur.execute('select state from cities where city = "pointer"')

Or better yet: 或者更好:

  day = cur.execute('select state from cities where city = ?',("pointer",))

EDIT 编辑

 urlstring = "select URL from cities where day is" + str(day)
 cur.execute(urlstring)
  1. Use the ? 使用 ? method I showed previously 我以前展示的方法
  2. You need a space after is 之后需要一个空格
  3. cur.execute() doesn't return the value like that. cur.execute()不会返回这样的值。 I'm not sure what it returns. 我不确定返回的内容。 You need to use a fetch method. 您需要使用提取方法。

Don't use double quotes. 不要使用双引号。 SQLite uses those to escape identifiers such as field and table names. SQLite使用这些字符来转义标识符,例如字段和表名。 Use single quotes instead. 请改用单引号。 Furthermore, you should use = instead of is : 此外,您应该使用=代替is

day = cur.execute("select state from cities where city = 'pointer'")

UPDATE : cur.execute() returns the cursor cur , not a result from the query. UPDATEcur.execute()返回游标cur ,而不是查询的结果。 You need to call cursor.fetchone() to get the value: 您需要调用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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM