插入是否最佳?

时间:2011-11-18 18:13:52

标签: python insert sqlalchemy

我想在表格中插入一些数据,我希望多次插入尽可能快。我使用sqlalchemy库进行Python。我想知道我的插入是否是最佳的,或者有更好的方法来做到这一点。这是我的代码:

 from sqlalchemy import *
    from sqlalchemy import schema

    metadata = schema.MetaData()

    engine = create_engine('sqlite:///:memory:', echo=True)

    users = Table('users', metadata,
        Column('id', Integer, primary_key=True),
        Column('firstname', String(40)),
        Column('lastname', Integer),
        )

    metadata.create_all(engine) 
    ins = users.insert()
    conn = engine.connect()

    conn.execute(users.insert(), [ 
      {'id': 1, 'firstname' : 'Name1', 'lastname' : 'Lname1'},
      {'id': 2, 'firstname' : 'Name2', 'lastname' : 'Lname2'},
      {'id': 3, 'firstname' : 'Name3', 'lastname' : 'Lname3'}
    ])

    metadata.bind = engine

1 个答案:

答案 0 :(得分:3)

如果您看到日志,那么您可以检查

2011-11-22 10:15:37,188 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2011-11-22 10:15:37,188 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,191 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'character_set%%'
2011-11-22 10:15:37,191 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,193 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2011-11-22 10:15:37,193 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,194 INFO sqlalchemy.engine.base.Engine SHOW COLLATION
2011-11-22 10:15:37,194 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,200 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2011-11-22 10:15:37,201 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,203 INFO sqlalchemy.engine.base.Engine DESCRIBE `users`
2011-11-22 10:15:37,203 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,204 INFO sqlalchemy.engine.base.Engine ROLLBACK
2011-11-22 10:15:37,206 INFO sqlalchemy.engine.base.Engine 
CREATE TABLE users (
    id INTEGER NOT NULL AUTO_INCREMENT, 
    firstname VARCHAR(40), 
    lastname INTEGER, 
    PRIMARY KEY (id)
)


2011-11-22 10:15:37,206 INFO sqlalchemy.engine.base.Engine ()
2011-11-22 10:15:37,331 INFO sqlalchemy.engine.base.Engine COMMIT
2011-11-22 10:15:37,333 INFO sqlalchemy.engine.base.Engine INSERT INTO users (id, firstname, lastname) VALUES (%s, %s, %s)
2011-11-22 10:15:37,333 INFO sqlalchemy.engine.base.Engine ((1, 'Name1', 'Lname1'), (2, 'Name2', 'Lname2'), (3, 'Name3', 'Lname3'))

只有一个包含所有值的插入,所以我认为这是插入批量/批量数据的最佳方式。