在MS Windows上,使用Python 3的pyodbc
模塊,我正在使用PostgreSQL。當我使用PostgreSQL的TEXT
數據類型並嘗試存儲類UNIX的EOL時,原始\n
被替換爲\r\n
。看下面的例子。PostgreSQL在文本字段中使用Python替換LF + CR + LF pyodbc
import pyodbc
def main():
connection = pyodbc.connect(
'DRIVER={PostgreSQL Unicode(x64)};'
'SERVER=127.0.0.1;'
'UID=postgres;'
'PWD=topsecret;'
'DATABASE=db1');
cursor = connection.cursor();
cursor.execute('CREATE SCHEMA schema1 '
'CREATE TABLE table1 ('
'key SERIAL PRIMARY KEY,'
'value TEXT'
')');
cursor.execute('INSERT INTO schema1.table1 (value) VALUES (?)',
'hello\nworld');
r = cursor.execute('SELECT value FROM schema1.table1').fetchone()[0];
print(r == 'hello\nworld'); # prints False
print(r == 'hello\r\nworld'); # prints True
if __name__ == '__main__':
main();
確實,這種行爲在某些情況下可能是有利的。但是,就我而言,這是不可取的。我無法找到如何在PostgreSQL的文檔中關閉此功能,並且我不確定替換是在哪裏發生的。有任何想法嗎?
爲什麼使用'pyodbc'而不是比較高級的'psycopg2'? –
另外,我會說轉換可能是在ODBC驅動程序。檢查DSN設置頁面。 –
@CraigRinger你是對的,我只是嘗試過''psycopg2''而不是''pyodbc'',LF→CR + LF不再發生。它真的在司機之內。 – Tregoreg