Home > Enterprise >  how to update latest post sqlite3?
how to update latest post sqlite3?

Time:12-11

I need to update the latest entry in the database. While the query works correctly in the DB browser, it doesn't work in code. Please tell me what's the matter?

class MySQL:
    def __init__(self):
        self.connection = sqlite3.connect(file_db, check_same_thread=False)
        self.cursor = self.connection.cursor()
        self.add_bd()     
    def update_sell_price(self, sell_price):
        with self.connection:
            self.cursor.execute(
                f'UPDATE Deals SET sell_price={sell_price}  ORDER BY deal_id DESC LIMIT 1')

Gives an error message: sqlite3.OperationalError: near "ORDER": syntax error

CodePudding user response:

The LIMIT and ORDER BY Clauses are available in the UPDATE statement only if SQLite is built with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option, which I suspect is not what you have in the version that you work with.

Instead use a scalar subquery to get the max deal_id:

sql = """
  UPDATE Deals 
  SET sell_price = ?
  WHERE deal_id = (SELECT MAX(deal_id) FROM Deals)
"""
self.cursor.execute(sql, (sell_price,))
  • Related