How To Connect The Database In Java
Connect the Database
- Register the driver class
The forName() method of Class registers, which is the driver class. It is used to dynamically load the driver class.
Syntax
public static void forName(String className)throws ClassNotFoundException
For example - Create the connection object
The getConnection() method of DriverManager class establishes the connection with the database.
Syntax
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password) throws SQLException
For example - Create the Statement object
The createStatement() method of the connection interface creates a statement. The object of the statement is mainly responsible to execute the queries with the database.
Syntax
public Statement createStatement()throws SQLException
For example - Execute the query
The executeQuery() method of statement interface executes queries to the database. It returns the object of ResultSet, which can be used to get all the records of a table.
Syntax
public ResultSet executeQuery(String sql)throws SQLException
For example - Close the connection object
The close() method of the connection interface closes the connection and by closing the connection object statement, ResultSet will also be closed automatically.
Syntax
public void close()throws SQLException
For example
Summary
Thus, we learnt, In JDBC, there are five steps to connect any Java Application with the database and also learnt how we can connect the database in Java.