最佳答案
我试图从字典插入数据到数据库。我希望遍历值并根据数据类型相应地格式化它们。下面是我正在使用的代码片段:
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
当我使用一些样本数据运行算法时(见下文),我得到了错误:
TypeError:序列项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]
我做错了什么?