問題:
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