【问题标题】:pyodbc query returns multiple backslashespyodbc 查询返回多个反斜杠
【发布时间】:2021-02-09 14:00:28
【问题描述】:

我正在尝试执行一个简单的查询,稍后我会将其写入 docx。 查询看起来像这样:

db_con = DB_CONNECTION()
with db_con.cursor() as cursor:
    cursor.execute("Select " + column + " \
                    FROM table.example \
                    WHERE code = '" + requirement +"' AND " + column + " != '';")

    rows = []
    for row in cursor.fetchall():
         rows.append(str(row)[2:-4])
return rows

在这种情况下,所有返回的行都是已收集的 cmets。其中一些包含换行符。 在数据库中,换行符保存为"\n"。使用 pyodbc 获取它们会导致它们返回为"\\n",在某些情况下返回为"\\\\n"。 (即使是同一行也可以在这两个选项之间进行更改)

有谁知道为什么 pyodbc 会这样做?或者我怎样才能避免这种情况?

我丑陋的解决方案是编写一个函数,它搜索"\\",如果找到 -> 搜索更多相邻的反斜杠并将它们全部替换为一个。

感谢您的帮助!

【问题讨论】:

    标签: python sql pyodbc


    【解决方案1】:

    您对 Python 的 表示 包含反斜杠的字符串感到困惑。

    >>> backsl = chr(0x5c)  # string containing a single backslash
    >>> hello = "Hello" + backsl + "n" + "world!"
    
    >>> # printing the string looks normal
    >>> print(hello)
    Hello\nworld!
    
    >>> the default string *representation* doubles up the backslash
    >>> hello
    'Hello\\nworld!'
    >>> str(hello)
    'Hello\\nworld!'
    
    # if you call `repr()` and then print() or str() that then the backslashes get doubled again
    >>> rep = repr(hello)
    >>> print(rep)
    'Hello\\nworld!'
    >>> rep
    "'Hello\\\\nworld!'"
    >>> str(rep)
    "'Hello\\\\nworld!'"
    

    请注意,仅将值转储到控制台(例如,>>> hello)会在其上执行隐式 str()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      相关资源
      最近更新 更多