简体   繁体   English

PostgreSQL使用Python pyodbc在TEXT字段中用CR + LF替换LF

[英]PostgreSQL replaces LF with CR+LF in TEXT fields using Python pyodbc

On MS Windows, using Python 3's pyodbc module, I'm working with PostgreSQL. 在MS Windows上,使用Python 3的pyodbc模块,我正在使用PostgreSQL。 When I use PostgreSQL's TEXT data type and attempt to store UNIX-like EOLs, the original \\n gets replaced with \\r\\n . 当我使用PostgreSQL的TEXT数据类型并尝试存储类似UNIX的EOL时,原始\\n将被替换为\\r\\n See the example below. 请参阅下面的示例。

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();

Indeed, such behavior might be advantageous in some cases. 实际上,在某些情况下,这种行为可能是有利的。 However, in my case, it's undesirable. 但是,就我而言,这是不可取的。 I was unable to find how to turn off this feature in PostgreSQL's docs, and am not actually sure where exactly the replacement takes place. 我无法在PostgreSQL的文档中找到如何关闭此功能,并且实际上并不确定替换发生在何处。 Any ideas? 有任何想法吗?

Most likely it's a behaviour of the ODBC driver its self, not the Python interface to it. 很可能它是ODBC驱动程序的行为,而不是它的Python接口。 That said, you're almost certainly better off using psycopg2 , which will be simpler, more powerful and faster. 也就是说,使用psycopg2几乎肯定会更好,这将更简单,更强大,更快。

Just like psqlODBC , psycopg2 wraps libpq but it does so without the clunky ODBC mid-layer. 就像psqlODBC一样, psycopg2包装libpq但它没有笨重的ODBC中间层。

Based on @CraigRinger's hint, I've been able to add new DSN, PostgreSQL35W , using %windir%\\system32\\odbcad32.exe . 根据@ CraigRinger的提示,我已经能够使用%windir%\\system32\\odbcad32.exe添加新的DSN, PostgreSQL35W The configuration allows us to turn off the LF ↔ CR/LF conversion as shown on the below screenshot: 配置允许我们关闭LF↔CR/ LF转换,如下面的屏幕截图所示:

PostgreSQL DNS的选项页面

Using DSN=PostgreSQL35W instead of DRIVER={PostgreSQL Unicode(x64)} fixed the problem. 使用DSN=PostgreSQL35W而不是DRIVER={PostgreSQL Unicode(x64)}修复了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM