Five Steps to connect a database via JDBC driver
|The fundamental steps involved in the process of connecting to a database and executing a query consist of the following:
- Load and register the JDBC driver
- Creating connection
- Create a statement object to process a query.
- Executing queries and processing the ResultSet
- Explicitly closing JDBC objects(resultset,statement & connection)
1) Load and register the JDBC driver
The forName() method of the java.lang.Class is used to load and register the JDBC driver:
public static void forName(String className)throws ClassNotFoundException
2) Create the connection object
The getConnection() method of java.sql.DriverManager is used to establish connection with database. It is an overloaded method that takes 3 parameters (URL, username, and password)
1) public static Connection getConnection(String url, String name, String password)
In case, when the URL contains the username and password then the following method is used
2) public static Connection getConnection(String url)throws SQLException
3) Create the Statement object
The createStatement() method of java.sql.Connection interface is used to create statement object which is responsible for running & executing queries against the database.
public Statement createStatement()throws SQLException
4) Executing the query and processing the ResultSet
Once a Statement object has been constructed, the next step is to execute the query. This is done by using the executeQuery() method of the Statement object. On executing this method it returns the object of ResultSet which contains the ResultSet produced by executing the query.
public ResultSet executeQuery(String sql)throws SQLException
Execute query and process the ResultSet
ResultSet rset=stmt.executeQuery("select * from employee");
// Processing the ResultSet
5) Explicitly closing JDBC objects
Once the Resultset,statement & Connection objects have been used, they must be closed explicitly. This is done by calling close() method of the ResultSet ,Statement and Connection classes.
public void close()throws SQLException
If you do not explicitly call the close() method for each of these objects as soon as you are done with them, your programs are likely to run out of resources. The best practice is to Close JDBC objects in finally block and assign null value afterwards, so that it will be immediately eligible for garbage collection.