【问题标题】:How to fix the psycopg2 syntax error at or near '%'?如何修复“%”处或附近的 psycopg2 语法错误?
【发布时间】:2020-01-06 21:36:43
【问题描述】:

基本上尝试创建 ISNERT 函数,该函数将编译插入并执行它。

def Insert(self,tablename, **kwargs):
        qms = []
        for idx, item in enumerate(kwargs):
            qms.append('%%s')
        qmarks = ', '.join(qms)
        res = []
        res.extend(kwargs.keys())
        res.extend(kwargs.values())
        res = tuple(res)
        QUERY = "INSERT INTO "+tablename+" (%s) VALUES (%s)" % (qmarks, qmarks)
        self.dc.execute(QUERY, res)
        self.db.commit()

返回我:

psycopg2.errors.SyntaxError: syntax error at or near "%"
LINE 1: INSERT INTO users (%s, %s) VALUES (%s, %s)

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    psycopg2 的execute() 函数只注入值而不是列,您需要将真实的列名传递给QUERY:

    import psycopg2
    import psycopg2.extras
    
    
    class A():
        def __init__(self):
            self.dc = ...
            self.db = ...
    
        def Insert(self, tablename, **kwargs):
            columns = []
            valuePlaceholders = []
            values = []
            for column, value in kwargs.items():
                columns.append(column)
                valuePlaceholders.append('%%s')
                values.append(value)
    
            QUERY = "INSERT INTO " + tablename + " (%s) VALUES (%s)" % (', '.join(columns), ', '.join(valuePlaceholders))
            print(self.db.mogrify(QUERY, values))
            #self.db.execute(QUERY, values)
            #self.db.commit()
    
    
    a = A().Insert('foo', arg1="bar", arg2="test")
    

    输出:

    b'INSERT INTO foo (arg1, arg2) VALUES (%s, %s)'
    

    【讨论】:

      【解决方案2】:

      您的 qms 数组中填充了字符串值“%s”。 然后您的 qmarks 字符串等于 '%s, %s'。 之后,您在查询字符串中注入该值两次,这样您就有了“INSERT INTO users (%s, %s) VALUES (%s, %s)”。 这里的问题是您用不正确的值填充了数组。 您需要注入表名和值而不是 %s

      【讨论】:

      • 它是格式化占位符。这应该不会导致问题。
      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2018-03-12
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多