Saturday, 10 December 2016

How to Connect to Database in Java?

In Java, we can connect Database using JDBC (Java Database Connectivity). To connect any database using JDBC we need the hostname, username, password etc. In few cases we need SID as well. 

The first important thing which is needed to connect any database is its JDBC Driver. There are four types of driver - Type I, II, III and IV. 

In our example, we are going to use thin driver and Oracle database in our example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
private static Connection connection = null;
// First way to Create JDBC Connection
public static Connection getConnection_1(String url, String userName, String password){
try {
connection = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(urluserNamepassword);
} catch (SQLException e) {

} catch (ClassNotFoundException e) {

}
 return connection;
}
// Second way to Create JDBC Connection 
public static Connection getConnection_2(String url, String userName, String password){
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection(url, userName, password);
} catch (SQLException e) {

}
return connection;
}

public static void main(String args[]) throws SQLException{
String sHost = "XXX.XX.XXX.XXX";
String sPort = "1521";
String sSid = "ANJAN";
String url = "jdbc:oracle:thin:@" + sHost + ":" + sPort + ":" + sSid;
String userName = "System";
String password = "1234";
Connection con1 = DBConnection.getConnection_1(url, userName, password);
if(con1 != null){
System.out.println("Connected");
con1.close();
}
Connection con2 = DBConnection.getConnection_2(url, userName, password);
if(con2 != null){
System.out.println("Connected");
con2.close();
}
 
}
}


Output -

Connected
Connected

No comments:

Post a Comment