问题在于确保您的代码始终使用相同的数据库连接。然后,您可以将其设置为适合当前环境的任何内容。
与其在方法之间传递数据库连接,不如将其设为单例可能更有意义。
def already_exists(story_data):
# Here `connection` is a singleton which returns the database connection.
connection.execute("""SELECT COUNT(*) from posts where post_id = ?""", (story_data.post_id,))
(number_of_rows,) = connection.fetchone()
if number_of_rows > 0:
return True
return False
或者connection
在每个类上做一个方法,然后already_exists
变成一个方法。无论如何,它可能应该是一种方法。
def already_exists(self):
# Here the connection is associated with the object.
self.connection.execute("""SELECT COUNT(*) from posts where post_id = ?""", (self.post_id,))
(number_of_rows,) = self.connection.fetchone()
if number_of_rows > 0:
return True
return False
但实际上你不应该自己滚动这段代码。相反,您应该使用诸如SQLAlchemy之类的ORM ,它会为您处理类似这样的基本查询和连接管理。它有一个连接,即“会话”。
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Address, Base, Person
engine = create_engine('sqlite:///sqlalchemy_example.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
然后你用它来进行查询。例如,它有一个exists
方法。
session.query(Post.id).filter(q.exists()).scalar()
使用 ORM 将大大简化您的代码。这是一个简短的基础教程,还有一个更长更完整的教程。