Connect To Database in Java
Connect To Database in Java
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 1/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 2/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
in the classpath, and then JDBC driver manager can detect and load the driver automatically.
Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the
database.
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 3/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database. This
method returns the object of ResultSet that can be used to get all the records of a table.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 4/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
← Prev Next →
AD
Feedback
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 5/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
Preparation
Company Questions
Trending Technologies
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 6/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
B.Tech / MCA
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 7/8
6/2/24, 4:07 PM How to connect to database in Java | Java Database Connectivity - javatpoint
AD
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java 8/8