我正在尝试将字典中的数据插入数据库。我想根据数据类型迭代这些值并相应地格式化它们。这是我正在使用的代码片段:
def _db_inserts(dbinfo):
try:
rows = dbinfo['datarows']
for row in rows:
field_names = ",".join(["'{0}'".format(x) for x in row.keys()])
value_list = row.values()
for pos, value in enumerate(value_list):
if isinstance(value, str):
value_list[pos] = "'{0}'".format(value)
elif isinstance(value, datetime):
value_list[pos] = "'{0}'".format(value.strftime('%Y-%m-%d'))
values = ",".join(value_list)
sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)
except Exception as e:
print 'BARFED with msg:',e
当我使用一些示例数据(见下文)运行算法时,出现错误:
类型错误:序列项 0:预期字符串,找到 int
给出上述错误的 value_list 数据的示例是:
value_list = [377, -99999, -99999, 'f', -99999, -99999, -99999, 1108.0999999999999, 0, 'f', -99999, 0, 'f', -99999, 'f', -99999, 1108.0999999999999, -99999, 'f', -99999, 'f', -99999, 'f', 'f', 0, 1108.0999999999999, -99999, -99999, 'f', 'f', 'f', -99999, 'f', '1984-04-02', -99999, 'f', -99999, 'f', 1108.0999999999999]
我究竟做错了什么?