使用 Python 驱动程序连接
使用官方 Neo4j Python 驱动程序,从 Python 应用程序连接到 Neo4j 数据库
使用 Python 驱动程序连接 是 CoddyKit 上的免费 Neo4j Graph Database Fundamentals 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Neo4j Graph Database Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Neo4j Graph Database Fundamentals 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Welcome: Connect Python & Neo4j
Welcome! In this lesson, you'll learn how to connect your Python applications to a Neo4j graph database.
A database driver acts as a bridge, allowing your code to send queries and receive data from the database.
Why Python for Neo4j?
Python is a popular choice for many applications, especially in data science and web development. Its simplicity and extensive libraries make it ideal for interacting with Neo4j.
- Ease of Use: Python's syntax is beginner-friendly.
- Data Ecosystem: Integrates well with other data tools.
- Official Driver: Neo4j provides a robust, well-maintained Python driver.
Install the Neo4j Python Driver
First, you need to install the official Neo4j Python driver. We use pip, Python's package installer, for this.
Open your terminal or command prompt and run:
pip install neo4j
This command downloads and installs the necessary libraries to your Python environment.
Neo4j Connection URI
To connect, your application needs to know where your Neo4j database lives. This is specified using a Connection URI.
For a local Neo4j instance, the common URI is bolt://localhost:7687.
bolt://: The protocol used by Neo4j for client communication.localhost: The address where Neo4j is running (your computer).7687: The default port for the Bolt protocol.
Your First Driver Instance
Now let's create a basic driver instance. This object manages the connection pool to your Neo4j database.
Try running this example:
from neo4j import GraphDatabase
uri = "bolt://localhost:7687" # Default local Neo4j URI
driver = None
try:
# Create a driver instance
driver = GraphDatabase.driver(uri)
print("Driver created successfully!")
except Exception as e:
print(f"Error creating driver: {e}")
finally:
if driver:
driver.close() # Always close the driver
print("Driver closed.")Authentication: Login to Neo4j
Most Neo4j databases require authentication (a username and password) to ensure only authorized users can access the data.
When you first set up Neo4j, it often uses a default user like neo4j and a password you set during installation.
You'll provide these credentials when initializing the driver.
Connect with Authentication
To connect with authentication, simply pass an auth tuple containing your username and password to the GraphDatabase.driver() method.
Remember to replace "your_password" with your actual Neo4j password!
from neo4j import GraphDatabase
uri = "bolt://localhost:7687"
username = "neo4j"
password = "your_password" # Replace with your Neo4j password
driver = None
try:
# Create a driver instance with authentication
driver = GraphDatabase.driver(uri, auth=(username, password))
print("Driver created with authentication!")
except Exception as e:
print(f"Error creating driver: {e}")
finally:
if driver:
driver.close()
print("Driver closed.")Best Practice: 'with' Statement
Python's with statement is excellent for managing resources that need to be explicitly closed, like database drivers.
Using with ensures the driver is automatically closed when you exit the block, even if errors occur. This prevents resource leaks.
from neo4j import GraphDatabase
uri = "bolt://localhost:7687"
username = "neo4j"
password = "your_password" # Replace with your Neo4j password
try:
# Use 'with' for automatic driver closing
with GraphDatabase.driver(uri, auth=(username, password)) as driver:
print("Driver created and will close automatically.")
# You can now use the 'driver' object here
# (e.g., to create sessions and run queries)
except Exception as e:
print(f"Error connecting: {e}")Troubleshooting Common Issues
If you encounter connection problems, here are common things to check:
- Neo4j Running? Ensure your Neo4j database is started.
- URI Correct? Double-check the host and port in your URI.
- Credentials? Verify the username and password are correct.
- Firewall? Your system's firewall might be blocking port 7687.
- Driver Installed? Confirm
pip install neo4jran successfully.
Check Your Understanding
Which of the following are necessary parameters when initializing the Neo4j Python driver for a secured connection?
Recap: Python Driver Connection
Great job! You've learned the essentials of connecting Python to Neo4j.
- Install the driver with
pip install neo4j. - Use a Connection URI like
bolt://localhost:7687. - Initialize the driver with
GraphDatabase.driver(), includingauthfor secured connections. - Employ the
withstatement for robust driver management.
Next, you'll learn how to execute Cypher queries using this driver!
常见问题解答
「使用 Python 驱动程序连接」课时是免费的吗?
是的 — 「使用 Python 驱动程序连接」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Neo4j Graph Database Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Neo4j Graph Database Fundamentals 课程共包含 4 节课。
「使用 Python 驱动程序连接」这节课中我会学到什么?
使用官方 Neo4j Python 驱动程序,从 Python 应用程序连接到 Neo4j 数据库 你通过在浏览器中直接运行的动手代码来练习 Neo4j Graph Database Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Neo4j Graph Database Fundamentals 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Neo4j Graph Database Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「使用 Python 驱动程序连接」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Neo4j Graph Database Fundamentals 课中编写并运行代码吗?
能。每节 Neo4j Graph Database Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 Python 驱动程序连接
- 以编程方式执行 CRUD 操作
- 处理事务与会话
- 连接池与错误处理