Home > Back-end >  Python and PostGres | Showing data in a QLabel (psycopg2)
Python and PostGres | Showing data in a QLabel (psycopg2)

Time:07-05

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

CodePudding user response:

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()

CodePudding user response:

It's just like this

print(row[0])

in your 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:
            #row without the brackets                            
            self.s_test.setText(str(row[0]))
            row = cur.fetchone()            
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
  • Related