如何查看Neo4j Python驱动当前连接的数据库?
解决Neo4j Python驱动查看当前连接数据库及指定操作数据库的问题
问题背景
我在Neo4j多数据库模式下使用Python脚本进行数据推送与拉取,需要指定脚本操作的数据库名称,同时希望能查看驱动当前连接的是哪个数据库。目前我的代码仅能验证连接并获取版本、主机和端口信息,无法得到数据库名称:
from neo4j import GraphDatabase # create the uri for the connection uri = "neo4j://localhost:7687" # create a driver object driver = GraphDatabase.driver(uri, auth=("neo4j", "password")) print("driver created") # get info about the driver print("connected: {}".format(driver.verify_connectivity())) print("Host: {}".format(driver.default_host)) print("Port: {}".format(driver.default_port)) # close the driver driver.close()
执行后verify_connectivity()仅返回版本信息:
connected: Neo4j/4.4.11
解决方案
一、查看当前连接的数据库
Neo4j Python驱动没有直接提供获取当前连接数据库名称的属性,需要通过执行Cypher查询来获取。以下是两种常用方法:
方法1:查询当前会话使用的数据库
通过db.name()函数直接返回当前会话对应的数据库名称:
from neo4j import GraphDatabase uri = "neo4j://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "password")) with driver.session() as session: result = session.run("RETURN db.name() AS current_database") current_db = result.single()["current_database"] print(f"当前连接的数据库: {current_db}") driver.close()
方法2:查看所有数据库及状态
通过SHOW DATABASES查询可以查看所有数据库的信息,包括名称、状态以及是否为默认数据库:
from neo4j import GraphDatabase uri = "neo4j://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "password")) with driver.session() as session: result = session.run("SHOW DATABASES") for record in result: print(f"数据库名称: {record['name']}, 状态: {record['status']}, 是否默认: {record['default']}") driver.close()
二、指定脚本操作的数据库
如果需要操作特定数据库,有两种实现方式:
1. 创建会话时指定数据库
在创建session对象时,通过database参数直接指定目标数据库,该会话内的所有操作都将针对此数据库:
from neo4j import GraphDatabase uri = "neo4j://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "password")) # 指定操作your_target_db数据库 with driver.session(database="your_target_db") as session: # 执行数据操作 session.run("CREATE (n:Test {name: 'Demo'})") # 验证当前操作的数据库 result = session.run("RETURN db.name() AS current_db") print(f"当前操作的数据库: {result.single()['current_db']}") driver.close()
2. 设置驱动的默认数据库
在创建driver对象时,通过default_database参数设置默认连接的数据库,后续所有未指定数据库的会话都会默认使用该数据库:
from neo4j import GraphDatabase uri = "neo4j://localhost:7687" # 设置默认连接your_default_db数据库 driver = GraphDatabase.driver(uri, auth=("neo4j", "password"), default_database="your_default_db") with driver.session() as session: result = session.run("RETURN db.name() AS current_db") print(f"驱动默认连接的数据库: {result.single()['current_db']}") driver.close()
内容的提问来源于stack exchange,提问作者Tono Kuriakose
相关产品推荐
相关产品推荐

