Home > Software design >  Python psycopg2 | Count plus in database
Python psycopg2 | Count plus in database

Time:07-06

I got a PyQt5 GUI with a spinbox and a button. I already wrote a statement that writes the number, thats in the spinbox in the database, when I click my button. Sadly it substitutes my old value. In my database I got a value named "hours". Let's say the value right now is 12. And if I click my button now it should add my number from the spinbox I typed in the GUI to the 12.

    def test():
        conn = None
        try:
            conn = psycopg2.connect("dbname=ueberstunden user=postgres password=admin")
            value = self.box_test.value()
            cur = conn.cursor()
            cur.execute("UPDATE ueberstunden SET stunden = %s WHERE name ='test'", value)
            conn.commit()
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        finally:
            if conn is not None:
                conn.close()

CodePudding user response:

You can use expressions on the right side of an assignment. Here, you'd want to assign studen with the current value, i.e., studen plus the new value:

cur.execute("UPDATE ueberstunden SET stunden = studen   %s WHERE name ='test'", value)
# Here ----------------------------------------^
  • Related