如何将python字典中的所有元素添加到数据库中?

时间:2016-01-07 20:38:07

标签: python sqlalchemy

我正在尝试将字典的元素添加到数据库中。我对使用数据库完全不熟悉,我只是想知道我是否做得对,因为在我看来并非如此。如果是这样,我该怎么办?那我怎么打印数据库的所有元素呢?

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() 

3 个答案:

答案 0 :(得分:1)

您的代码已基本完成。您可以在验证后查询数据库。

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

输出:

1 John doctor  
2 Alice typist

答案 1 :(得分:1)

还有另一种方法可以在不使用for周期的情况下将Python Dict直接插入数据库,也许这可以帮助您。

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

dict_values是一个Python Dict,其键名与数据库列完全相同。例如:{'name': "John Doe", 'job': "Programmer"}或一系列字母,例如:[{'name': "John Doe", 'job': "Programmer"}, {...}, ...]

选中此示例以获取更多示例:Optimize Inserts Using SQLAlchemy

答案 2 :(得分:0)

您无需为每个项目创建新会话:

LANG=ru_RU.UTF-8 wine program.exe