简体   繁体   中英

Syntax error in retrieving data from SQLite

When running the following code I get a sqlite3.OperationalError: near XX error...

The code is in python and is the following:

def get(item_id='', table='groups', field='id', encrypt=True):
    conn = sqlite3.connect('data.db')
    c = conn.cursor()
    if item_id == '':
        sqlstr = 'SELECT * FROM {}'.format(table)
        c.execute(sqlstr)
    else:
        if encrypt:
            item_id = encryption.encrypt(item_id)
        sqlstr = "SELECT * FROM {} WHERE {}={}".format(table, field, item_id)
        c.execute(sqlstr)

considering as variables the following:

  • table = 'groups'
  • field = 'id'
  • encrypt = True and considering that the value returned by encryption.encrypt(item_id) is 'gAAAAABe7UPHni1WJ1pSaljNj30k_SX-xGEfyCNMwO-3Pgjm1I57ROxSq5liNnm8yk5pjv0ZY7SyTUMIYqZrOyLeLQZNZ63iMw==', I get the following error:
Traceback (most recent call last):
  File "d:\dhfwi\Projects\FridaysForFuture\fff-transparency-wg\.env\lib\site-packages\telegram\utils\promise.py", line 57, in run
    self._result = self.pooled_function(*self.args, **self.kwargs)
  File "d:\dhfwi\Projects\FridaysForFuture\fff-transparency-wg\fff_automation\bots\telebot\editgroup.py", line 10, in edit_group
    group = database.get(chat_id)[0]
  File "d:\dhfwi\Projects\FridaysForFuture\fff-transparency-wg\fff_automation\modules\database.py", line 149, in get
    c.execute(sqlstr)
sqlite3.OperationalError: near "'gAAAAABe7UPHni1WJ1pSaljNj30k_SX-xGEfyCNMwO-3Pgjm1I57ROxSq5liNnm8yk5pjv0ZY7SyTUMIYqZrOyLeLQZNZ63iMw=='": syntax error

I tried adding '' around the {} of the item_id field in the sqlstr,

sqlstr = "SELECT * FROM {} WHERE {}='{}'".format(table, field, item_id)

but by doing that, I get the following error:

Traceback (most recent call last):
  File "d:\dhfwi\Projects\FridaysForFuture\fff-transparency-wg\.env\lib\site-packages\telegram\utils\promise.py", line 57, in run
    self._result = self.pooled_function(*self.args, **self.kwargs)
  File "d:\dhfwi\Projects\FridaysForFuture\fff-transparency-wg\fff_automation\bots\telebot\editgroup.py", line 10, in edit_group
    group = database.get(chat_id)[0]
  File "d:\dhfwi\Projects\FridaysForFuture\fff-transparency-wg\fff_automation\modules\database.py", line 149, in get
    c.execute(sqlstr)
sqlite3.OperationalError: near "gAAAAABe7Ue7Yg6OP2ipWHGAXfZCiCVgbpdPso3noPYCjW4ds9rY8Yg9HN0Dhm10DDh7wYQ3kf2OuSabHlxcrg5xzwEdO4V31Q": syntax error

Consider passing item_id as a parameter with qmark placeholder since quote confusion may be the issue:

sqlstr = "SELECT * FROM {} WHERE {}=?".format(table, field)
# sqlstr = f"SELECT * FROM {table} WHERE {field}=?"    # F-String (Python 3.6+)

c.execute(sqlstr, (item,))

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