事务不可重用:>>> trans = conn.begin()
2018-03-29 09:14:33,001 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
>>> trans.commit()
2018-03-29 09:14:35,449 INFO sqlalchemy.engine.base.Engine COMMIT
>>> trans.commit()
Traceback (most recent call last):
File "", line 1, in
File "/home/u/sqlalchemy/lib/sqlalchemy/engine/base.py", line 1642, in commit
raise exc.InvalidRequestError("This transaction is inactive")
sqlalchemy.exc.InvalidRequestError: This transaction is inactive
>>> trans.rollback()
>>>
您必须在第一个事务之后启动新事务,或者在同一事务中执行所有操作。在
另一方面,这并不能解释为什么复制失败。在上一个显式事务结束后,连接返回到autocommit。换句话说,如果没有事务正在进行,则引擎或连接将提交。但问题是:autocommit是基于检测数据更改操作的,这是由matching the given statement针对执行的
^{pr2}$
正如您可能注意到的,COPY不是regexp的一部分。如前所述,最好的选择是启动另一个显式事务,或者在同一个事务中执行两个操作。但是,如果您希望在将来的某个时候对COPY使用autocommit,请指示SQLAlchemy它应该自动提交:conn.execute(text("COPY ...").execution_options(autocommit=True))
至于后一个错误,FROM file并没有神奇地访问Python变量,而是一个语法错误。将文件名作为参数传递给查询:copy_stmt = text("COPY table_name FROM :file WITH CSV HEADER")
copy_stmt = copy_stmt.execution_options(autocommit=True)
conn.execute(copy_stmt, {"file": file})
请注意,COPY from a file需要您可能不应拥有的特权:COPY naming a file or command is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.file = "/home/user/csvfile.csv"
stmt = "COPY table_name FROM STDIN CSV HEADER"
raw_conn = eng.raw_connection()
# Uses the actual psycopg2 connection as a context manager
# for transaction handling.
with open(file) as f, \
raw_conn.connection, \
raw_conn.cursor() as cur:
cur.copy_expert(stmt, f)
raw_conn.close()