简体   繁体   中英

Python code to load json data into database SQLAlchemy

I have created a database using SQLAlchemy which column names business_id , useful.

class Review(Base):
    __tablename__ = 'rev'
    id=Column(Integer,primary_key=True)
    business_id = Column(String(50))
    useful = Column(Integer)
    # initial_rating=Column(Integer)

engine = create_engine('sqlite:///sqlalchemy_try.db')
Base.metadata.create_all(engine)

Now i have a json file and i want to load the business id and useful present in json file into this database.I have opened the json file but dont know how to load it in this database:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import  Base, Review

engine = create_engine('sqlite:///sqlalchemy_try.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)

session = DBSession()
with open('rev.json') as f:
    data=f.read()
    jsondata=json.loads(data)

I'd suppose something like this:

r = Review(int(jsondata['id']), jsondata['business_id'], int(jsondata['useful']))
session.add(r)

In the end, add session.commit() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM