1 Q Steps to connect a Java
Application to Database:
There are 6 steps to connect any java application with the database using JDBC.
These steps are as follows:
Import a package named java.sql
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
1 Import package:
The first and essential step to create JDBC connection is to
import a package named java.sql in your java application.
This package provides various interfaces and classes that
are used by jdbc API for accessing and processing data
stored in a data source using java code.
Import java.sql.*; // java code
2 Register the Driver class:
After adding package to your java code.The forName() method of Class class is used to
register the driver class. This method is used to dynamically load the driver class.
For example, to load and register the driver to establish database connection with MySQL,
following code is used in java program:
Class.forName(“com.mysql.jdbc.Driver”);
3 Create a Connection:
In this step, we will establish/create a connection to
database using getConnection() method of DriverManager class.
Example to establish connection with the MySql database:
Connection con =
DriverManager.getConnection("jdbc:mysql://localhos
t:3306/database","username","password");
If confused with blue box go to book pg 13.4
4 Create the Statement object:
After establishing connection in step 3 , now the createStatement()
method of Connection interface is used to create statement object . The object of statement
is responsible to execute queries with the database.
Example to create the statement object
Statement stmt=con.createStatement(); // java code
5 Execute the query:
After creating statement object, Use the executeQuery() method of
the Statement object to execute a SQL query. This method returns
a ResultSet object that contains the results of the query.
6 Closing the connection:
This is final step which includes closing all the connection
that we opened in our previous steps. The close() method of
Connection interface is used to close the connection.
con.close();
This step ensures that all resources are released.