Cristian Muñoz
Cristian Muñoz

Reputation: 610

Why am I not able to obtain response from querying a string using cursor.execute using psycopg2?

I am using Python2.7 through Spyder (Anaconda2(64-bit)).

I establish connection with a PostgreSQL database using:

conn = psycopg2.connect(dbname='dbname',host='host',port='5433', user='postgres', password='password')

If I try to query the database it works fine with numbers:

cursor.execute('SELECT platform.platform_id,platform.platform_name FROM instrumentation.platform WHERE platform_id=15;')
cursor.fetchone()

giving me the response: (15L, 'Station_LaMola') which is what I expected.

However, when I try to query looking for the name, it reports me the well known error:

value = 'Station_LaMola'
cursor.execute("SELECT platform.platform_name FROM instrumentation.platform WHERE platform_name = '%s'",(value,))

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128)

Apparently this is the proper way to perform the query. What am I doing wrong?

Thanks in advance

Upvotes: 1

Views: 60

Answers (1)

alecxe
alecxe

Reputation: 473863

Define it as unicode string and remove the quotes around the placeholder:

value = u'Station_LaMola'
cursor.execute("""
    SELECT 
        platform.platform_name 
    FROM 
        instrumentation.platform 
    WHERE 
        platform_name = %s""", (value, ))

Upvotes: 1

Related Questions