I have seen a lot of database connections, most of which have problems, some are unavailable, here is given a database connection plant, giving JDBC1 and JDBC2 implementation, for reference only!
public class ConnectionFactory_JDBC1 {private static String url = "jdbc: oracle: thin: @ 218.12.7.35: 1521: myorcl"; private static String user = "developer"; private static String password = "developer"; static {try {Class. forName ( "oracle.jdbc.driver.OracleDriver");} catch (ClassNotFoundException e) {throw new RuntimeException ( "Could not load database driver!");}} static Connection getConnection () throws SQLException {return DriverManager.getConnection (url, User, password);} public static void closeconnection (connection conn) {if (conn! = null) {Try {conn.close ();} catch (SQLEXCEPTION E) {// There is no need to handle}}}}}}}
The above connection is an Oracle database, of course, the username and password here and the URL you can also get through the configuration file, although only a few lines
Code, for new hands, it is not easy to fully understand, if it is possible to use JDBC2 method as possible.
public class ConnectionFactory_JDBC2 {private static String dbName = "jdbc / mydb"; private static DataSource ds; static {try {Context ctx = new InitialContext (); ds = (DataSource) ctx.lookup (dbName);} catch (NamingException e) {throw new RuntimeException ( "data not available source!");}} public static Connection getConnection () throws SQLException {return ds.getConnection ();} public static void closeConnection (Connection conn) {if (! conn = null) { Try {conn.close ();} catch (sqlexception e) {// no need to handle}}}}