代码之家  ›  专栏  ›  技术社区  ›  arcee123

将dict none推送到sql null

  •  0
  • arcee123  · 技术社区  · 6 年前

    我有一段代码:

    def get_summary_data(self):
        summary_data = self.page_data.find('table', {'class': 'GroupBox1'})
        record = {}
        rows = summary_data.findAll('tr')
        for row in rows:
            fields = row.findAll('td')
            for field in fields:
                key = field.find(text=True, recursive=False).strip()
                value = field.find('strong').text.strip() if field.find('strong') else None
                value = value if value else None
                if key != '':
                    record[self.configuration[key]] = value
        ins_qry = "INSERT INTO {tablename} ({columns}) VALUES {values};".format(
            tablename='rrc_completion_data.summarydata',
            columns=', '.join(record.keys()),
            values=tuple(record.values())
        )
        self.engine.execute(ins_qry)
    

    生成的查询如下所示:

    INSERT INTO rrc_completion_data.summarydata (Track_No, Status, Operator_Nm, Compl_Type, Field_Nm, Completion_Dt, Lease_Nm, Filing_Purpose, District_No, Well_Type, LeaseNo, County, Well_No, WellBore_Profile, API, WB_Compl_Type, DrilL_Permit_No, SL_Parent_Drill_Permit_No, Field_No, Horiz_Depth_Severance) VALUES ('2928', 'Work in Progress', 'WILLIAMS PROD. GULF COAST, L.P. (924558)', 'New Well', 'NEWARK, EAST (BARNETT SHALE)', '05/17/2010', 'DR. BOB SMITH A NORTH', 'Initial Potential', '09', 'Producing', None, 'DENTON', '10H', 'HORIZONTAL', '42-121-33861', None, '687311', None, '65280200', None);
    

    正如您所看到的,我正试图将none的值用作空值。但会导致以下错误:

    sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "none" does not exist
    LINE 1: ...A NORTH', 'Initial Potential', '09', 'Producing', None, 'DEN...
    

    我错过了什么?我的目的是在数据库表中不存在空值。

    谢谢

    0 回复  |  直到 6 年前
        1
  •  1
  •   Ilja Everilä    6 年前

    问题的根源是使用字符串格式将值传递给sql查询。 从未 那样做。它使您接触到sql注入等。看起来您将列白名单了,这是很好的,但是随后传递用python包装的值 tuple 并相信字符串表示与SQL行构造的字符串表示匹配,这一点在 None 价值观。问题的另一个来源是包含 ' 性格。

    相反,您应该在查询字符串中使用占位符,并让库处理将值传递给sql:

    columns = list(record.keys())
    ins_qry = "INSERT INTO rrc_completion_data.summarydata ({columns}) VALUES ({placeholders})".format(
        columns=', '.join(columns),
        placeholders=', '.join([':' + c for c in columns])
    )
    self.engine.execute(text(ins_qry), record)