I am moving the code that interacts with my Neo4J database into a separate python module so I can stop repeating myself in other modules.
The problem I am having is that in each function call in the new module I am having to have a separate call to...
db = Graph('http://localhost/db/data')
...to establish a connection to the database.
This seems really silly and is not solving my goal of reducing the amount of unnecessary code.
Normally, I would establish the connection in the main function but because this module is being called from elsewhere I can't do this.
I am looking for a way of establishing a local variable that will persist between function calls, so I can forget about connecting to the db.
Apart from code bloat you are making it extremely inefficient by having every function connect to a database. If you want to stick with procedural programming, then make it a global variable. With classes you can either connect in the __init__
method or pass database connection to __init__
as an argument. Most of my classes support both:
class A:
def __init__(self, ..., db_connection=None):
self.db_connection = db_connection or DbConnection()
...
def f(self):
self.db_connection("SELECT A from B")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.