如何解决如果“价格”列没有值,则在将 csv 插入 postgresql 时跳过行的快速方法?
这是我的代码示例,只是想知道如果“价格”列为空,是否可以轻松跳过插入中的一行,如果是,将不胜感激任何建议!
def insert_data():
drop_table_if_exists()
#create table
cursor.execute("create table IF NOT EXISTS %s (%s);" % (tbl_name,col_str))
with open(file_path,newline='') as csvfile:
reader = csv.reader(csvfile)
next(csvfile)
for row in reader:
print(row)
cursor.execute("INSERT INTO %s (%s) \
VALUES (%%s,%%s,%%s)" \
% (tbl_name,cols),row[:16])
time.sleep(1)
#make public
cursor.execute('''grant select on table %s to public''' % (tbl_name))
conn.commit()
print('im in the loop')
解决方法
想通了,只需要添加if all(row)。如果有任何空列,它会删除一行,它没有指定哪一列,但足够接近:
for row in reader:
print(row)
if all(row):
cursor.execute("INSERT INTO %s (%s) \