使用SQLAlchemy将多个实例插入数据库时​​键入错误

时间:2018-06-13 08:50:41

标签: python sqlite sqlalchemy

所以我得到一个包含员工信息的列表列表,我想将其写入数据库。 SQLAlchemy documuntation说它的正确,现在但DB仍然是空的。数据库是正确创建的,我现在可以如何插入数据 employees_list到数据库?

我的代码

from PyBambooHR import PyBambooHR
import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
import pprint


Base = declarative_base()


class EmployeeData(Base):

    __tablename__ = 'employee_data'
    id = Column(Integer, primary_key=True)
    name = Column(String(120))
    department = Column(String(120))
    jobTitle = Column(String(120))
    email = Column(String(120))


engine = sqlalchemy.create_engine('sqlite:///employee_db.db')

connection = engine.connect()


Base.metadata.create_all(engine)

bamboo = PyBambooHR(subdomain='company', api_key='key')


employees = bamboo.get_employee_directory()
employees_list = [[item['displayName'], item['department'], item['jobTitle'], item['workEmail']] for item in employees]


employees_list.sort()

connection.execute(employees_list.insert())

connection.close()

pprint.pprint(employees_list)

原因

Traceback (most recent call last):
  File "...", line 37, in <module>
    connection.execute(employees_list.insert())
TypeError: insert() takes exactly 2 arguments (0 given)

1 个答案:

答案 0 :(得分:0)

您当前的问题是您使用的list.insert方法与 SQLAlchemy 无关。

如果需要使用 SQLAlchemy 将对象正确插入数据库,则可以打开数据库Session,创建EmployeeData个实例,将它们添加到会话并提交更改。

为此,我们可以按如下方式定义EmployeeData初始化程序

class EmployeeData(Base):
    __tablename__ = 'employee_data'
    id = Column(Integer, primary_key=True)
    name = Column(String(120))
    department = Column(String(120))
    jobTitle = Column(String(120))
    email = Column(String(120))

    def __init__(self, name, department, jobTitle, email):
        self.name = name
        self.department = department
        self.jobTitle = jobTitle
        self.email = email

打开Session

from sqlalchemy.orm import Session, sessionmaker
...
session_factory = sessionmaker(engine)
session = session_factory()

创建EmployeeData个实例

employees_list = [EmployeeData(name=item['displayName'],
                               department=item['department'],
                               jobTitle=item['jobTitle'],
                               email=item['workEmail'])
                  for item in employees]

添加EmployeeData个实例&amp;提交更改

session.add_all(employees_list)
session.commit()

测试

由于我无法访问Bamboo服务,因此我会模仿回复

employees = [{'displayName': 'John Doe',
              'department': 'IT',
              'jobTitle': 'Python Developer',
              'workEmail': 'jdoe@company.com'}]

按照上述步骤,我在工作目录中获得了employee_db.db SQLite 数据库。让我们使用 SQLite CLI (来自SQLite tools

打开它
sqlite> .open employee_db.db
sqlite> select * from employee_data;
1|John Doe|IT|Python Developer|jdoe@company.com

进一步阅读