Se connecter avec le pilote Python
Établissez une connexion à votre base de données Neo4j depuis une application Python à l’aide du pilote Python officiel de Neo4j.
Se connecter avec le pilote Python est une leçon Neo4j Graph Database Fundamentals gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Neo4j Graph Database Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Neo4j Graph Database Fundamentals comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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!
Questions Fréquemment Posées
La leçon « Se connecter avec le pilote Python » est-elle gratuite ?
Oui — le texte complet de « Se connecter avec le pilote Python » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Neo4j Graph Database Fundamentals, passe à CoddyKit PRO. Le cours Neo4j Graph Database Fundamentals comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Se connecter avec le pilote Python » ?
Établissez une connexion à votre base de données Neo4j depuis une application Python à l’aide du pilote Python officiel de Neo4j. Tu pratiques Neo4j Graph Database Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Neo4j Graph Database Fundamentals ?
Aucune expérience préalable n'est requise. Neo4j Graph Database Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Se connecter avec le pilote Python » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Neo4j Graph Database Fundamentals ?
Oui. Chaque leçon Neo4j Graph Database Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Se connecter avec le pilote Python
- Effectuer des opérations CRUD par programmation
- Gérer les transactions et les sessions
- Regroupement des connexions et gestion des erreurs