初学python的小白
json文件如下:
[
{
"_id": "55501245ef21cb978435bdb0",
"index": 0,
"guid": "316f9bb8-1e0e-4b02-ad41-bc2e65966a26",
"balance": "$1,115.97",
"age": 34,
"eyeColor": "brown",
"name": "Manning Schroeder",
"gender": "male",
"about": "Commodo cupidatat occaecat aliquip mollit deserunt fugiat ad sint magna ex anim nisi deserunt anim. Nulla laborum excepteur velit ad sit adipisicing esse minim. Pariatur aliquip reprehenderit adipisicing cupidatat anim labore minim ut.\r\n",
"tags": [
"exercitation",
"amet",
"quis",
"consequat"
],
"friends": [
{
"id": 0,
"name": "Mandy Erickson"
},
{
"id": 1,
"name": "Lang Cooper"
},
{
"id": 2,
"name": "Hill Alvarado"
}
],
"greeting": "Hello, Manning Schroeder! You have 1 unread messages.",
"favoriteFruit": "banana"
},
我现在能会读单个元素,但是在拼接字符串的时候,总是出错,球大神解答。
我的代码如下:
import json,pprint
with open('/Users/xxxosx/Downloads/1.json','r') as jf:
jdata = json.load(jf)
content = 'insert into xxx values'
for i in jdata:
a= {i["_id"],",",i["index"],",",i["guid"],",",i["isActive"],",",i["balance"],i["picture"],i["age"],i["eyeColor"],
i["name"],i[blahblah]}
content =content.join(a)
print content
for j in range(3):
print i["friends"][j]["id"],i["friends"][j]["name"]
1
Septembers 2015-05-11 12:53:12 +08:00
建议你去玩MongoDB(我是来歪楼的
|
2
miaomiaomiaoa OP @Septembers 。。我是玩oracle11g得。。
|
3
fangjinmin 2015-05-11 13:13:23 +08:00
a=[i["_id"],i["index"],i["guid"],i["isActive"],i["balance"],i["picture"],i["age"],i["eyeColor"],
i["name"],i[blahblah]] content = content + "(" + ",".join(a) + ")" |
4
fzinfz 2015-05-11 20:37:11 +08:00
为了LZ的视力着想,建议以后不要string join了,改用%s吧~
范例: http://mysql-python.sourceforge.net/MySQLdb.html c.executemany( """INSERT INTO breakfast (name, spam, eggs, sausage, price) VALUES (%s, %s, %s, %s, %s)""", [ ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ), ("Not So Much Spam Plate", 3, 2, 0, 3.95 ), ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 ) ] ) |
5
fzinfz 2015-05-11 20:41:11 +08:00
这有个更好的: http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
add_salary = ("INSERT INTO salaries " "(emp_no, salary, from_date, to_date) " "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)") # Insert salary information data_salary = { 'emp_no': emp_no, 'salary': 50000, 'from_date': tomorrow, 'to_date': date(9999, 1, 1), } cursor.execute(add_salary, data_salary) |