I have read a lot of database connection code, most of which have problems and some are even completely unavailable. Here we provide a database connection factory and implementation of jdbc1 and jdbc2 for your 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 ("the database driver cannot be loaded! ");
}
}
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 ){
// No need to handle
}
}
}
}
The above is connected to the oracle database, of course, here the user name and password and url can also be obtained through the configuration file, although only a few lines
It is not easy for new users to fully understand the code. If possible, try to use the JDBC2 method.
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 ("the data source cannot be obtained! ");
}
}
Public static Connection getConnection () throws SQLException {
Return ds. getConnection ();
}
Public static void closeConnection (Connection conn ){
If (conn! = Null ){