【问题标题】:Python & pymysql: Database Table with hyphen in namePython & pymysql:名称中带有连字符的数据库表
【发布时间】:2019-08-10 23:59:14
【问题描述】:

我需要从mysql数据库中查询数据,表名包含连字符。

current_table = "tw3-10_1"
sql2 = "SELECT * FROM " + str(current_table ) 
cursor.execute(sql2)

不幸的是,我得到: 1064, "您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,以了解在第 1 行的 '-10_1' 附近使用的正确语法")

有没有办法解决这个问题?不幸的是,我无法更改表格的名称.....

【问题讨论】:

  • 也许在反引号 `tw3-10_1` 中引用表名会有所帮助。

标签: python sql mariadb pymysql


【解决方案1】:

您通常可以使用反引号来引用表名或列名,以防它包含无用的字符。

current_table = "`tw3-10_1`"
sql2 = "SELECT * FROM " + current_table

或者如果你喜欢

current_table = "tw3-10_1"
sql2 = "SELECT * FROM `{}`".format(current_table)

【讨论】:

  • 非常感谢。我尝试了这两种方法,我不再收到错误但不知何故,如果我后来这样做,我会得到一个空元组:cursor.execute(sql2) 然后 current_data = cursor.fetchall(),如果我将表名更改为一个没有连字符我得到数据
【解决方案2】:

尝试这样,我不了解 MariaDB,但引号应该在 SQL 中工作

sql2 = """
    SELECT
            *
    FROM "{table_name}"
    """.format(
            table_name='table-with-hyphens'
        )
print(sql2)
    # SELECT
    #         *
    # FROM "table-with-hyphens"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 2018-10-25
    • 2010-10-29
    • 1970-01-01
    • 2011-11-26
    • 2018-10-18
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多