1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
import java.sql.*;
public class Singleton {
/*
* La méthode getInstance n'est sûr pour les threads
* (possibilité de créer plusieurs Singleton) donc
* on a besoin de sécuriser celle-ci avec synchronized.
*/
public static synchronized Singleton getInstance(){
if (instance == null)
instance = new Singleton();
return instance;
}
private Connection con;
private Singleton(){
try {
//Register the JDBC driver for MySQL.
Class.forName("com.mysql.jdbc.Driver");
//Define URL of database server for
// database named mysql on the localhost
// with the default port number 3306.
String url = "jdbc:mysql://localhost:3306/delphi";
//Get a connection to the database for a
// user named root with a blank password.
// This user is the default administrator
// having full privileges to do anything.
con = DriverManager.getConnection(url,"root", "root");
//Display URL and connection information
System.out.println("URL: " + url);
System.out.println("Connection: " + con);
//Get a Statement object
//stmt = con.createStatement();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
System.out.println("Construction du Singleton");
}
private static Singleton instance;
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
}
public Connection getCon() {
return con;
}
} |
Partager