简体   繁体   中英

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.

Any ideas or pointers? Thanks in advance.

SQLite follows the SQL standard: strings are enclosed in single quotes, not double quotes. Also, generally use = to check for string equality.

Only use is in sql when checking for null

  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. 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. Use single quotes instead. Furthermore, you should use = instead of is :

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

UPDATE : cur.execute() returns the cursor cur , not a result from the query. You need to call cursor.fetchone() to get the value:

# 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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