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
|
public JDBCConnector(String driver, String URL, String username, String password)
throws ClassNotFoundException {
try {
// initialisation du contexte
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
InitialContext ic = new InitialContext();
// création d'une référence sur la DataSource
Reference ref = new Reference("javax.sql.DataSource",
"com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory",
null);
ref.add(new StringRefAddr("driverClassName", driver));
ref.add(new StringRefAddr("url", URL));
ref.add(new StringRefAddr("username", username));
ref.add(new StringRefAddr("password", password));
// liaison de la DataSource au contexte
ic.rebind("jdbc/MaDataSource", ref);
// récupération de la DataSource à partir du contexte
Context ctx = new InitialContext();
DataSource source = (DataSource) ctx.lookup("jdbc/MaDataSource");
// récupération d'une Connection
Connection conn = (Connection) source.getConnection();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} |