【发布时间】:2014-08-16 01:03:27
【问题描述】:
我正在尝试使用 MySQLdb 将 JSON 字符串中的数据插入 MySQL。总列数是固定的。 JSON 字符串中的每一行数据并不总是每列都有值。
这是我的示例代码:
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 错误。这是因为这些值没有用引号括起来 (')。
想解决的问题?
【问题讨论】:
标签: python mysql mysql-python sql-insert