问题:
I am attempting to insert data from a dictionary into a database.我正在尝试将字典中的数据插入到数据库中。 I want to iterate over the values and format them accordingly, depending on the data type.我想根据数据类型迭代这些值并相应地格式化它们。 Here is a snippet of the code I am using:这是我正在使用的代码片段:
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
When I run the algo using some sample data (see below), I get the error:当我使用一些示例数据(见下文)运行算法时,出现错误:
TypeError: sequence item 0: expected string, int found类型错误:序列项 0:预期的字符串,找到整数
An example of a value_list data which gives the above error is:给出上述错误的 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]
What am I doing wrong?我究竟做错了什么?
解决方案:
参考一: https://en.stackoom.com/question/jeaz参考二: https://stackoom.com/question/jeaz