我試圖用MySQLdb將數據從JSON字符串插入到MySQL。列的總數是固定的。 JSON字符串中的每行數據並不總是具有每列的值。當使用MySQL-Python將JSON數據插入MySQL時出現TypeError
這裏是我的示例代碼:
vacant_building = 'http://data.cityofchicago.org/resource/7nii-7srd.json?%24where=date_service_request_was_received=%272014-06-02T00:00:00%27'
obj = urllib2.urlopen(vacant_building)
data = json.load(obj)
def insert_mysql(columns, placeholders, data):
sql = "INSERT INTO vacant_buildings (%s) VALUES (%s)" % (columns, placeholders)
db = MySQLdb.connect(host="localhost", user="xxxx", passwd="xxxx", db="chicago_data")
cur = db.cursor()
cur.execute(sql, data)
for row in data:
placeholders = ', '.join(['%s'] * len(row))
columns = ', '.join(c[:64] for c in row.keys())
row_data = ', '.join(str(value) for value in row.values())
insert_mysql(columns, placeholders, row_data)
我得到以下錯誤:
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
我敢肯定的錯誤與我插入值的方式去做。我試圖將其更改爲:
sql = "INSERT INTO vacant_buildings (%s) VALUES (%s) (%s)" % (columns, placeholders, data)
但我得到了1064錯誤。這是因爲這些值沒有用引號括起來('
)。
想法解決?