Skip to content
Advertisement

Python and PostGres | Showing data in a QLabel (psycopg2)

im using Postgres together with python(psycopg2). Im trying to insert data in a QLabel. It shows the data, but the data comes with clinges. How do I get rid of the clinges?

My code:

    def getstunden():
        conn = None
        try:
            conn = psycopg2.connect("dbname=test user=postgres password=test")
            cur = conn.cursor()
            cur.execute("SELECT stunden FROM ueberstunden WHERE name = 'test'")
            row = cur.fetchone()

            while row is not None:
                self.s_test.setText(str(row))
                row = cur.fetchone()
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        finally:
            if conn is not None:
                conn.close()

This is what I get out of it:

I want it to just show 12

Advertisement

Answer

Per here Cursor:

Note

cursor objects are iterable, so, instead of calling explicitly fetchone() in a loop, the object itself can be used:

cur.execute(“SELECT * FROM test;”) for record in cur: print record

(1, 100, “abc’def”)

(2, None, ‘dada’)

(3, 42, ‘bar’)

So to simplify:

 def getstunden():
        conn = None
        try:
            conn = psycopg2.connect("dbname=test user=postgres password=test")
            cur = conn.cursor()
            cur.execute("SELECT stunden FROM ueberstunden WHERE name = 'test'")
            for row in cur:
                self.s_test.setText(str(row[0]))
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        finally:
            if conn is not None:
                conn.close()

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement