Convert CSV Blank cell to SQL NULL in Python

蓝咒 提交于 2019-12-11 06:22:09

问题


I'm trying to convert blank cells in a csv file to NULL and upload them in SQL Server table so it shows as NULL rather blank. below code works but they load NULL as a string. Can you please help me to modify the code so it loads NULL in SQL ?

reader = csv.reader(f_in)    # setup code
writer = csv.writer(f_out)

row = next(reader)           # handle first line (with no replacements)
writer.writerow(row)
last_row = row               # always save the last row of data that we've written
variable = None

for row in reader:           # loop over the rest of the lines
    row = [x if x else "NULL" for x, y in zip(row, last_row)]  # replace empty strings
    writer.writerow(row)
    last_row = row




with open(outputFileName,'r') as fin: # `with` statement available in 2.5+    
dr = csv.DictReader(fin) # comma is default delimiter        
to_db = [(i['SubFund'], 
        i['Trader'], 
        i['Prime Broker/Clearing Broker']) 

cur.executemany("INSERT INTO Citco_SPOS (" + 
            "subfund, " +
           "trader, " +
            "prime_broker_clearing_broker, " + +
            "VALUES (?, ?,  ?);", to_db)
con.commit()

回答1:


This should work

import pyodbc
import csv
cnxn = pyodbc.connect(connection string)
cur = cnxn.cursor()
query = "insert into yourtable values(?, ?)"
with open('yourfile.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        for i in range(len(row)):
            if row[i] == '':
                row[i] = None
        cur.execute(query, row)   
    cur.commit()


来源:https://stackoverflow.com/questions/41473612/convert-csv-blank-cell-to-sql-null-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!