【neo4j】python使用neo4j

本文介绍了如何通过Neo4j的Python接口建立连接,执行Cypher查询(如MATCHnRETURNnLIMIT10),并展示了从Neo4j数据库获取数据的基本步骤。最后,展示了关闭连接的方法。
摘要由CSDN通过智能技术生成
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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值