为什么我无法通过使用 psycopg2 使用 cursor.execute 查询字符串来获得响应?
Why am I not able to obtain response from querying a string using cursor.execute using psycopg2?
我正在通过 Spyder(Anaconda2(64 位))使用 Python2.7。
我使用以下方法与 PostgreSQL 数据库建立连接:
conn = psycopg2.connect(dbname='dbname',host='host',port='5433', user='postgres', password='password')
如果我尝试查询数据库,它可以很好地处理数字:
cursor.execute('SELECT platform.platform_id,platform.platform_name FROM instrumentation.platform WHERE platform_id=15;')
cursor.fetchone()
给我回复:(15L, 'Station_LaMola') 这正是我所期望的。
但是,当我尝试查询名称时,它向我报告了众所周知的错误:
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)
显然这是执行查询的正确方法。我做错了什么?
提前致谢
将其定义为 unicode 字符串并删除占位符周围的引号:
value = u'Station_LaMola'
cursor.execute("""
SELECT
platform.platform_name
FROM
instrumentation.platform
WHERE
platform_name = %s""", (value, ))
我正在通过 Spyder(Anaconda2(64 位))使用 Python2.7。
我使用以下方法与 PostgreSQL 数据库建立连接:
conn = psycopg2.connect(dbname='dbname',host='host',port='5433', user='postgres', password='password')
如果我尝试查询数据库,它可以很好地处理数字:
cursor.execute('SELECT platform.platform_id,platform.platform_name FROM instrumentation.platform WHERE platform_id=15;')
cursor.fetchone()
给我回复:(15L, 'Station_LaMola') 这正是我所期望的。
但是,当我尝试查询名称时,它向我报告了众所周知的错误:
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)
显然这是执行查询的正确方法。我做错了什么?
提前致谢
将其定义为 unicode 字符串并删除占位符周围的引号:
value = u'Station_LaMola'
cursor.execute("""
SELECT
platform.platform_name
FROM
instrumentation.platform
WHERE
platform_name = %s""", (value, ))