Steps to connect a Java Application to Database
The following 5 steps are the basic steps involve in connecting a Java application with Database using JDBC.
- Register the Driver
- Create a Connection
- Create SQL Statement
- Execute SQL Statement
- Closing the connection
Register the Driver
Class.forName()
is used to load the driver class explicitly.
Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Create a Connection
getConnection()
method of DriverManager class is used to create a connection.
Syntax
getConnection(String url) getConnection(String url, String username, String password) getConnection(String url, Properties info)
Example establish connection with Oracle Driver
Connection con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE","username","password");
Create SQL Statement
createStatement()
method is invoked on current Connection object to create a SQL Statement.
Syntax
public Statement createStatement() throws SQLException
Example to create a SQL statement
Statement s=con.createStatement();
Execute SQL Statement
executeQuery()
method of Statement interface is used to execute SQL statements.
Syntax
public ResultSet executeQuery(String query) throws SQLException
Example to execute a SQL statement
ResultSet rs=s.executeQuery("select * from user"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); }
Closing the connection
After executing SQL statement you need to close the connection and release the session. The
close()
method of Connection interface is used to close the connection.
Syntax
public void close() throws SQLException
Example of closing a connection
con.close();