Simple database connection factory implementation

Source: Internet
Author: User

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 ){

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.