connexion java à sql server avec eclipse TP2
Étape 1 : Téléchargement et installation des outils
1.1 Installer SQL Server Express
1. Téléchargez SQL Server Express : https://www.microsoft.com/fr-fr/sql-server/sql-server-downloads
2. Exécutez l'installateur et sélectionnez "Installation de base"
3. Installer avec les options par défaut en fournissant le mot de passe pour l’utilisateur « sa » en
choisissant ‘Authentification mixte’
1.2 Installer SQL Server Management Studio (SSMS)
1. Téléchargez SSMS : https://aka.ms/ssmsfullsetup
2. Installez avec les options par défaut
1.3 Installer Eclipse IDE
1. Téléchargez Eclipse : https://www.eclipse.org/downloads/
2. Choisissez "Eclipse IDE for Enterprise Java and Web Developers"
3. Installez avec les options par défaut
1.4 Télécharger le driver JDBC
1. Téléchargez le driver Microsoft JDBC : https://docs.microsoft.com/fr-fr/sql/connect/jdbc/download-
microsoft-jdbc-driver-for-sql-server
2. Choisissez la version correspondant à votre Java (ex: mssql-jdbc-12.2.0.jre11.jar)
Étape 2 : Configuration de SQL Server
2.1 Activer TCP/IP
1. Ouvrez "SQL Server Configuration Manager"
2. Développez "Configuration du réseau SQL Server"
3. Cliquez sur "Protocoles pour MSSQLSERVER"
4. Activez "TCP/IP"
5. Définir le port 1433 pour IPAll.
6. Redémarrez le service SQL Server
2.2 Configurer le pare-feu
1. Ouvrez "Pare-feu Windows avec fonctions avancées de sécurité"
2. Créez une règle de trafic entrant pour le port 1433 (port par défaut SQL Server)
2.3 Vérifier la connexion avec SSMS
1. Lancez SSMS
2. Connectez-vous avec :
o Type de serveur : Moteur de base de données
o Nom du serveur : localhost ou .\SQLEXPRESS
o Authentification : SQL Server Authentication
mme BENSIDI AHMED 1
connexion java à sql server avec eclipse TP2
o Login : sa
o Mot de passe : celui que vous avez défini
o
Étape 3 : Création de la base de données et table
3.1 Créer la base de données
Dans SSMS, exécutez :
CREATE DATABASE GestionClients;
USE GestionClients;
CREATE TABLE Clients (
id INT PRIMARY KEY IDENTITY(1,1),
nom VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
telephone VARCHAR(20),
date_creation DATETIME DEFAULT GETDATE()
);
INSERT INTO Clients (nom, email, telephone) VALUES
(BENSIDI AHMED',
[email protected]', '123456789'),
('BENSADEK',
[email protected]', '987654321');
Étape 4 : Configuration du projet Eclipse
4.1 Créer un nouveau projet Java
1. Lancez Eclipse
2. File → New → Java Project
3. Nommez-le "GestionClients"
4. Cliquez sur Finish
4.2 Ajouter le driver JDBC
1. Clic droit sur le projet → Build Path → Configure Build Path
2. Onglet Libraries → Add External JARs
3. Sélectionnez le fichier mssql-jdbc-*.jar téléchargé
4. Cliquez sur Apply and Close
mme BENSIDI AHMED 2
connexion java à sql server avec eclipse TP2
Étape 5 : Code Java complet
5.1 Créer une classe de connexion utilitaire
package com.example.sqlserver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=GestionClients;
encrypt=true;trustServerCertificate=true";
private static final String USER = "sa";
private static final String PASSWORD = "votre_mot_de_passe";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
5.2 Créer une classe principale pour les opérations CRUD
package com.example.sqlserver;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class ClientManager {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
boolean running = true;
while (running) {
System.out.println("\nGestion des Clients");
System.out.println("1. Lister tous les clients");
System.out.println("2. Ajouter un client");
System.out.println("3. Mettre à jour un client");
System.out.println("4. Supprimer un client");
System.out.println("5. Quitter");
System.out.print("Choix : ");
int choix = scanner.nextInt();
scanner.nextLine(); // consommer la nouvelle ligne
mme BENSIDI AHMED 3
connexion java à sql server avec eclipse TP2
try {
switch (choix) {
case 1:
listClients();
break;
case 2:
addClient();
break;
case 3:
updateClient();
break;
case 4:
deleteClient();
break;
case 5:
running = false;
break;
default:
System.out.println("Option invalide");
}
} catch (SQLException e) {
System.err.println("Erreur SQL : " + e.getMessage());
}
}
System.out.println("Programme terminé.");
}
private static void listClients() throws SQLException {
String sql = "SELECT * FROM Clients ORDER BY nom";
try (Connection conn = DatabaseConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("\nListe des clients :");
System.out.println("ID\tNom\t\tEmail\t\t\tTéléphone\tDate création");
while (rs.next()) {
System.out.printf("%d\t%s\t%s\t%s\t%s%n",
rs.getInt("id"),
rs.getString("nom"),
rs.getString("email"),
rs.getString("telephone"),
rs.getTimestamp("date_creation"));
}
}
}
private static void addClient() throws SQLException {
mme BENSIDI AHMED 4
connexion java à sql server avec eclipse TP2
System.out.println("\nAjout d'un nouveau client");
System.out.print("Nom : ");
String nom = scanner.nextLine();
System.out.print("Email : ");
String email = scanner.nextLine();
System.out.print("Téléphone : ");
String telephone = scanner.nextLine();
String sql = "INSERT INTO Clients (nom, email, telephone) VALUES (?, ?, ?)";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, nom);
pstmt.setString(2, email);
pstmt.setString(3, telephone);
int rows = pstmt.executeUpdate();
System.out.println(rows + " client ajouté avec succès.");
}
}
private static void updateClient() throws SQLException {
System.out.println("\nMise à jour d'un client");
System.out.print("ID du client à modifier : ");
int id = scanner.nextInt();
scanner.nextLine();
System.out.print("Nouveau nom (laissez vide pour ne pas modifier) : ");
String nom = scanner.nextLine();
System.out.print("Nouvel email (laissez vide pour ne pas modifier) : ");
String email = scanner.nextLine();
System.out.print("Nouveau téléphone (laissez vide pour ne pas modifier) : ");
String telephone = scanner.nextLine();
StringBuilder sql = new StringBuilder("UPDATE Clients SET ");
boolean needsComma = false;
if (!nom.isEmpty()) {
sql.append("nom = ?");
needsComma = true;
}
if (!email.isEmpty()) {
if (needsComma) sql.append(", ");
sql.append("email = ?");
needsComma = true;
}
if (!telephone.isEmpty()) {
if (needsComma) sql.append(", ");
sql.append("telephone = ?");
}
mme BENSIDI AHMED 5
connexion java à sql server avec eclipse TP2
sql.append(" WHERE id = ?");
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql.toString())) {
int paramIndex = 1;
if (!nom.isEmpty()) {
pstmt.setString(paramIndex++, nom);
}
if (!email.isEmpty()) {
pstmt.setString(paramIndex++, email);
}
if (!telephone.isEmpty()) {
pstmt.setString(paramIndex++, telephone);
}
pstmt.setInt(paramIndex, id);
int rows = pstmt.executeUpdate();
if (rows > 0) {
System.out.println("Client mis à jour avec succès.");
} else {
System.out.println("Aucun client trouvé avec cet ID.");
}
}
}
private static void deleteClient() throws SQLException {
System.out.println("\nSuppression d'un client");
System.out.print("ID du client à supprimer : ");
int id = scanner.nextInt();
scanner.nextLine();
String sql = "DELETE FROM Clients WHERE id = ?";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
int rows = pstmt.executeUpdate();
if (rows > 0) {
System.out.println("Client supprimé avec succès.");
} else {
System.out.println("Aucun client trouvé avec cet ID.");
}
}
}
}
mme BENSIDI AHMED 6
connexion java à sql server avec eclipse TP2
Étape 6 : Exécution et test
1. Cliquez droit sur la classe ClientManager
2. Run As → Java Application
3. Testez les différentes fonctionnalités :
o Lister les clients existants
o Ajouter un nouveau client
o Modifier un client existant
o Supprimer un client
mme BENSIDI AHMED 7