SQLite3 + Python CSV DictReader:处理空值的最佳方法

时间:2014-10-31 18:49:12

标签: python csv sqlite

对Python来说还是新手,本月早些时候我遇到了一个问题,其中String' 0'被传递到我的整数列(使用SQLite数据库)。来自我原始帖子的更多信息:

SQL: Can WHERE Statement filter out specific groups for GROUP BY Statement

这导致我的SQL Query语句返回无效数据。

当CSV文件不包含特定单元格的任何值时,我在数据库的其他列中会弹出同样的问题。

我的数据来源是我下载的外部csv文件(unicode格式)。我使用以下代码将我的代码插入到DB中:

with sqlite3.connect(db_filename) as conn:

    dbcursor = conn.cursor()

    with codecs.open(csv_filename, "r", "utf-8-sig") as f:
        csv_reader = csv.DictReader(f, delimiter=',')

        #  This is a much smaller column example as the actual data has many columns.
        csv_dict = [( i['col1'], i['col2'] ) for i in csv_reader)

    dbcursor.executemany(sql_str, csv_dict)

根据我的研究,按设计,SQLite在插入值时不会强制执行列类型。我对原始问题的解决方案是进行手动检查以查看它是否为空值,然后使用此代码将其设为int 0:

def Check_Session_ID( sessionID ):

    if sessionID == '':
        sessionID = int(0)

    return sessionID

将值插入数据库时​​,需要检查每个整数/浮点列。由于每个导入(100K +)x(50+列)上会有很多行,我认为导入需要花费相当多的时间。

有哪些更好的方法来处理此问题,而不是每行检查每个Int / Float列的每个值?

非常感谢您的建议和指导。

0 个答案:

没有答案