gpt4 book ai didi

sqlite - SQLAlchemy 中的 ProgrammingError 线程错误

转载 作者:IT王子 更新时间:2023-10-29 06:30:40 25 4
gpt4 key购买 nike

我在 sqlite 数据库中有两个简单的表。

from sqlalchemy import MetaData, Table, Column, Integer, ForeignKey, \
create_engine, String
from sqlalchemy.orm import mapper, relationship, sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base

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

session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)
session = Session()

Base = declarative_base()

class NodeType(Base):
__tablename__ = 'nodetype'
id = Column(Integer, primary_key=True)
name = Column(String(20), unique=True)
nodes = relationship('Node', backref='nodetype')

def __init__(self, name):
self.name = name

def __repr__(self):
return "Nodetype: %s" % self.name


class Node(Base):
__tablename__ = 'node'

id = Column(Integer, primary_key=True)
name = Column(String(20), unique=True)
type_id = Column(Integer,
ForeignKey('nodetype.id'))


def __init__(self, _name, _type_id):
self.name = _name
self.type_id = _type_id

Base.metadata.create_all(engine)

运行结束后,我与口译员进行了互动。例如n1= Node('Node1',1) 了解 sqlalchemy。在我做了一个 session.commit() 并尝试另一个语句之后,例如n2 = Node('n2',1) 我收到这个错误:sqlalchemy.exc.ProgrammingError: (ProgrammingError) 在线程中创建的 SQLite 对象只能在同一线程中使用。该对象是在线程 ID 3932 中创建的,这是线程 ID 5740 无无。

提交后如何继续 session ?发送

最佳答案

默认情况下,SQLite 禁止在多个线程中使用单个连接。只需将 connect_args={'check_same_thread': False} 参数添加到您的 engine 变量中即可

engine = create_engine('sqlite:///dir_graph.sqlite', connect_args={'check_same_thread': False}, echo=True)

根据 sqlite3.connect :

By default, check_same_thread is True and only the creating thread may use the connection. If set False, the returned connection may be shared across multiple threads. When using multiple threads with the same connection writing operations should be serialized by the user to avoid data corruption.

关于sqlite - SQLAlchemy 中的 ProgrammingError 线程错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15140554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com