There are 5 steps to connect any java application with the database by using JDBC. They are as follows:
- Register the driver class
- Creating connection
- Creating statement
- Executing queries
- Closing connection
Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
public static void forName(String className)throws
Class.forName("oracle.jdbc.driver.OracleDriver");Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
1) public static Connection getConnection(String url)throws SQLException 2) public static Connection getConnection(String url,String name,String password) throws SQLException
Ex: Connect with Oracle
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.
public Statement createStatement()throws SQLException
Statement stmt=con.createStatement();Execute the query
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.
public ResultSet executeQuery(String sql)throws SQLException
ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)); }Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
public void close()throws SQLException
See Also :
- JDBC Connection with MySQL Database
- JDBC Connection with Oracle Database
- JDBC Connectivity with access without DSN (Data Source Name)
More on JDBC
Follow below links to learn more on JDBC and solving JDBC related issues :
You must log in to post a comment.