How to convert variable to String?

Asked

Viewed 431 times

2

I have a function that takes a postgresql database code and visualize setting in QLabel with the function setText().

The problem is that this code comes from the database in strange format, between parentheses and comma. Example: (VI1,).

How to remove these commas and parentheses?

Function:

def cod_via(self,nome_via):
    cursor = self.connectBanco()
    sql = "SELECT cod_via FROM espacial.via WHERE nome_via = '%s'"%nome_via 

    cursor.execute(sql)  
    resultado = cursor.fetchall()                   

    return resultado

Exhibit with:

cod = instancia_sql.cod_via(nome_via)

self.dlg.label_resul.setText(str(cod))

3 answers

1

It comes in the format of tuple.

You can catch him like this:

t = ('a', 'b', 1, 2);
t2 = (1, 2, 3, 4, 5, 6, 7 );

print "t[0]: ", t[0]
print "t2[1:5]: ", t2[1:5]

Upshot:

t[0]:  a
t2[1:5]:  [2, 3, 4, 5]

In your case try cod[0].

1

If not returning more than one result you can use the join:

return ''.join(resultado)

0


The problem is that this code comes from the database in format in brackets and comma. Example: (VI1,). How to remove these parentheses and commas?

This happens because the method cursor.fetchall() returns a list of tuples, the ideal is to use the method cursor.fetchone(), which will return a line or None. Behold:

def cod_via(self, nome_via):
    cursor = self.connectBanco()
    sql = "SELECT cod_via FROM espacial.via WHERE nome_via = '%s'" % nome_via 

    cursor.execute(sql)
    resultado = cursor.fetchone()

    return resultado
  • Staff solved. In addition to using fetchone() it is necessary to use Ope to traverse the result.

  • 1

    It looks like this: cursor.execute(sql) result = cursor.fetchone() for Resp in result: result=Resp; Return result

Browser other questions tagged

You are not signed in. Login or sign up in order to post.