python - 如何修复 '%' 处或附近的 psycopg2 语法错误?

标签 python postgresql psycopg2

基本上尝试创建 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)

最佳答案

psycopg2 的 execute() 函数仅注入(inject)值但不列,您需要将真实的列名称传递给 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)'

关于python - 如何修复 '%' 处或附近的 psycopg2 语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59610256/

相关文章:

python - 如何单步调试 Python 代码以帮助调试问题?

xml - 将 XML 数据导入 PostgreSQL 9.5.12、Ubuntu 16.04.4 的问题

python,访问psycopg2形式的def?

python - Psycopg2 连接 sql 数据库到 pandas 数据框

python-3.x - 使用 PostgreSQL copy_from、psycopg2 和 StringIO 批量插入

Python:匹配元组中的两个元素,返回第三个

python - 使用第二个数据框中的值从一个数据框中选择

python - 如何通过具有相同索引对子列表进行分组?

ruby-on-rails - 最近的价格和 will_paginate

postgresql - 如何在 Postgres 中批量插入忽略过程中可能发生的所有错误?