【问题标题】:To log error lines while inserting data into the postgres table from a text file using python使用 python 从文本文件将数据插入 postgres 表时记录错误行
【发布时间】:2011-09-05 09:04:42
【问题描述】:

我是 python 和 postgres 的新手。 我有一个从 csv 文件中读取数据并将数据插入到表中的代码。 该代码仅在文件中有无错误行时才有效。 但是,如果某些行中有任何错误,我希望 python 忽略这些行并将其余行插入表中。应将有错误的行写入单独的文件中。 代码如下:

import psycopg2
import csv

try:
    conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' 
    password='postgres'")
except:
    print "I am unable to connect to the database"

cur = conn.cursor()

filehandle = open('abc.csv', 'r') 
reader = csv.reader(filehandle, delimiter=',')

for row in reader:
    statement = "INSERT INTO abc(col1,col2,col3) VALUES ('%s', '%s','%s')" % (tuple(row))
    cur.execute(statement)

conn.commit() 

【问题讨论】:

  • 您是否真的建议您使用字符串操作将值替换为 SQL 查询? 忘掉它。如果该值包含'(这可能很容易在某一天发生),您最终会得到无效查询,甚至查询会做一些完全不同的事情,因为这是可怕的 SQL 注入攻击。
  • 事实上,使用参数甚至更容易。简单地说:cur.execute("INSERT ... VALUES (?, ?, ?)", *tuple(row)) 应该可以。这将负责根据需要引用值。
  • 抱歉,对于 PostgreSQL 的特殊情况,它不是?,而是%s(参见initd.org/psycopg/docs/usage.html#query-parameters)。

标签: python


【解决方案1】:

如果您检测到引发异常的错误,请尝试以下操作:

for row in reader:
    try:
        statement = "INSERT INTO abc(col1,col2,col3) VALUES ('%s', '%s','%s')" % (tuple(row))
        cur.execute(statement)
    except:
        #do the stuff in case of error

【讨论】:

  • 不要使用格式将值替换为 SQL,将参数作为额外参数传递给 execute。它更快、更容易,并且避免了 SQL 注入攻击的风险。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2014-01-12
  • 2012-12-17
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
相关资源
最近更新 更多