Skip to content Skip to sidebar Skip to footer

Convert Csv Blank Cell To Sql Null In Python

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 y

Solution 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()

Post a Comment for "Convert Csv Blank Cell To Sql Null In Python"