2012-07-04 44 views
0

当我使用psycopg2插入数据到PostgreSQL,我不能插入包含'\ x00'的字符串。为什么psycopg2不能像' x00'那样插入字符串?

这里是我的代码:

>>> import psycopg2 
>>> import psycopg2.extensions 
>>> conn = psycopg2.connect(database='test') 
>>> curs = conn.cursor() 
>>> print curs.mogrify('insert into test values (%s, %s)', 
     ('hello, buddy', 'str\x00str')) 
>>> curs.close() 
>>> conn.close() 

我能得到的字符串是这样的:

>>> ... 
>>> print curs.mogrify('insert into test values (%s, %s)', 
... ('hello, world', 'str\x00str')) 
insert into test values ('hello, world', 'str') 
>>> ... 

那么,哪里是 '\ x00str'?

但是,在psycopg2,我找到了一些关于 unicoding-handling

它显示['\ x01' - '\ xff]的作品。

这样的代码:

>>> ... 
>>> print curs.mogrify('insert into test values (%s, %s)', 
... ('hello, world', 'str\x01\x02\x03...\xffstr')) 
insert into test values ('hello, world', 'str\x01\x02\x03...\xffstr') 
>>> ... 

[问题]:这里是 '\ x00str'?我如何使字符串'\ x00'在psycopg2中工作?

+0

你试过'\\ x00'吗?它似乎'\ x00'可能会结束 – pinkdawn

+0

我试过'\\ x00'.It的作品。但是,当'\ x00 \ x01'变成'\\ x00 \\ x01'时,它们的长度不相等。 – leozhang

+1

\ x实际上是指python中的东西,十六进制;说\ x00 == 0,\ x0e == Oct 15;所以len('\ x00')= 1,len('\\ x00')= 4; '\\ x00'实际上意味着你想要保存的字符串 – pinkdawn

回答

1

问题是你试图在字符串中插入一个值为0的字符,PostgreSQL不支持字符数据(libpq返回字符串\ 0终止,我们没有办法区分你的\ 0来自真正的)。如果要插入任意数据(包括0),请使用bytea列和psycopg2二进制适配器。

请参阅http://www.psycopg.org/psycopg/docs/module.html#psycopg2.Binary

相关问题