How to add all elements from python dictionary to database?

六月ゝ 毕业季﹏ 提交于 2021-01-25 03:47:09

问题


I'm trying to add the elements of a dictionary to the database. I'm completely new to working with databases and I'm just wondering if I'm doing it right or not, because it seems to me that not. If so, how can I do it ? And how can I print all the elements of the database then ?

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key = True)
    name = Column(String(250), nullable=False)
    job = Column(String(250), nullable=False)

engine = create_engine('sqlite:///persons.sqlite')
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)

dct = {'John':'doctor', 'Alice':'typist'}

for el in dct:
    np = Person(name=el, job=dct[el])
    s = session()
    s.add(np)
    s.commit() 

回答1:


Your code is almost complete. You can query your db after to verify.

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    job = Column(String(250), nullable=False)

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

session = sessionmaker(bind=engine)
s = session()

dct = {'John': 'doctor', 'Alice': 'typist'}

for key, value in dct.items():
    np = Person(name=key, job=value)
    s.add(np)

s.commit()

db_result = s.query(Person).all()
for row in db_result:
    print row.id, row.name, row.job

Output:

1 John doctor  
2 Alice typist



回答2:


There is another way to insert a Python Dict directly into the database without using the for cycle, maybe this can help you.

session.execute(Person.__table__.insert(), dict_values))
session.commit()

dict_values is a Python Dict with the keys named exactly as the data base columns. Ex: {'name': "John Doe", 'job': "Programmer"} or a list of dicts, ex: [{'name': "John Doe", 'job': "Programmer"}, {...}, ...]

Check this for more examples: Optimize Inserts Using SQLAlchemy




回答3:


You don't need to create a new session for each item:

s = session()
for name, job in dct.iteritems():
    np = Person(name=name, job=job)
    s.add(np)
    s.commit() 


来源:https://stackoverflow.com/questions/34664700/how-to-add-all-elements-from-python-dictionary-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!