问题
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