【neo4j】python使用neo4j

发布时间:2024年01月19日
from neo4j import GraphDatabase

class Neo4jConnection:
    
    def __init__(self, uri, user, pwd):
        self.__uri = uri
        self.__user = user
        self.__password = pwd
        self.__driver = None
        try:
            self.__driver = GraphDatabase.driver(self.__uri, auth=(self.__user, self.__password))
        except Exception as e:
            print("Failed to create the driver:", e)
    
    def close(self):
        if self.__driver is not None:
            self.__driver.close()
    
    def query(self, query, parameters=None, db=None):
        assert self.__driver is not None, "Driver not initialized!"
        session = None
        response = None
        try:   
            session = self.__driver.session(database=db) if db is not None else self.__driver.session() 
            response = list(session.run(query, parameters))
        except Exception as e:
            print("Query failed:", e)
        finally:
            if session is not None:
                session.close()
        return response

# 连接到 Neo4j
conn = Neo4jConnection(uri="xxxxxxxx", user="xxxxxxx", pwd="xxxxxxx")

# 执行一个查询
query_string = "MATCH (n) RETURN n LIMIT 10"
results = conn.query(query_string)

# 输出查询结果
for record in results:
    print(record)

# 关闭连接
conn.close()
文章来源:https://blog.csdn.net/qq_42725437/article/details/135698429
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。