STEPS TO CONNECT TO A DATABASE
Now, we shall learn step-by-step process to connect a database using Java. The
interface and classes of the JDBC API are present inside the package called as java.sql
interface and classes of the JDBC API are present inside the package called as java.sql
code.
import java.sql.* ;
STEP 1: Load the Drivers
=The first step in accessing the database is to load an appropriate driver. You can use
one driver from the available four drivers which are described earlier. However,
one driver from the available four drivers which are described earlier. However,
JDBC-ODBC Driver is the most preferred driver among developers. If you are using
any other type of driver, then it should be installed on the system (usually this requires
having the driver jWe can also register the driver (if third party driver) with the use of method
having the driver jWe can also register the driver (if third party driver) with the use of method
registerMethod() whose syntax is as follows :
DriverManager.registerDriver(Driver dr);
Where dr is the new JDBC driver to be registered with the DriverManager.
There are a number of alternative ways to do the actual loading:
DriverManager.registerDriver(Driver dr);
Where dr is the new JDBC driver to be registered with the DriverManager.
There are a number of alternative ways to do the actual loading:
1. Use new to explicitly load the Driver class. This hard codes the driver and
(indirectly) the name of the database into your program and is not recommended
as changing the driver or the database or even the name or location of the
database will usually require recompiling the program.
(indirectly) the name of the database into your program and is not recommended
as changing the driver or the database or even the name or location of the
database will usually require recompiling the program.
2. Class.forName takes a string class name and loads the necessary class
dynamically at runtime as specified in the above example. This is a safe method
that works well in all Java environments although it still requires extra coding to
avoid hard coding the class name into the program.
dynamically at runtime as specified in the above example. This is a safe method
that works well in all Java environments although it still requires extra coding to
avoid hard coding the class name into the program.
3. The System class has a static Property list. If this has a Property jdbc.drivers set
to a ':' separated list of driver class names, then all of these drivers will be
loaded and registered automatically. Since there is support for loading property
lists from files easily in Java, this is a convenient mechanism to set up a whole
set of drivers. When a connection is requested, all loaded drivers are checked to
see which one can handle the request and an appropriate one is chosen.
Unfortunately, support for using this approach in servlet servers is patchy so we
will stay with method 2 above but use the properties file method to load the
database url and the driver name at runtime:
to a ':' separated list of driver class names, then all of these drivers will be
loaded and registered automatically. Since there is support for loading property
lists from files easily in Java, this is a convenient mechanism to set up a whole
set of drivers. When a connection is requested, all loaded drivers are checked to
see which one can handle the request and an appropriate one is chosen.
Unfortunately, support for using this approach in servlet servers is patchy so we
will stay with method 2 above but use the properties file method to load the
database url and the driver name at runtime:
Properties props = new Properties() ;
FileInputStream in = new FileInputStream(“Database.Properties”) ;
props.load(in)
FileInputStream in = new FileInputStream(“Database.Properties”) ;
props.load(in)
String drivers = props.getProperty("jdbc.drivers") ;
Class.forName(drivers) ;
Class.forName(drivers) ;
The Database.Properties file contents look like this:
# Default JDBC driver and database specificationjdbc.drivers =
sun.jdbc.odbc.JdbcOdbcDriverdatabase.Shop = jdbc:odbc:Shop
sun.jdbc.odbc.JdbcOdbcDriverdatabase.Shop = jdbc:odbc:Shop
STEP 2: Make the Connection
The getConnection() method of the Driver Manager class is called to obtain the
Connection Object. The syntax looks like this:
Connection Object. The syntax looks like this:
Connection conn = DriverManager.getConnection("jdbc:odbc:<DSN NAME>");
Here note that getConnection() is a static method, meaning it should be accessed
along with the class associated with the method. The DSN (Data Source name) Name
is the name, which you gave in the Control Panel->ODBC while registering the
Database or Table.
Here note that getConnection() is a static method, meaning it should be accessed
along with the class associated with the method. The DSN (Data Source name) Name
is the name, which you gave in the Control Panel->ODBC while registering the
Database or Table.
STEP 3: Create JDBC Statement
A Statement object is used to send SQL Query to the Database Management System.
You can simply create a statement object and then execute it. It takes an instance of
active connection to create a statement object. We have to use our earlier created
Connection Object “conn” here to create the Statement object “stmt”. The code looks
like this:
You can simply create a statement object and then execute it. It takes an instance of
active connection to create a statement object. We have to use our earlier created
Connection Object “conn” here to create the Statement object “stmt”. The code looks
like this:
Statement stmt = conn.createStatement();
As mentioned earlier we may use Prepared Statement or callable statement according
to the requirement
As mentioned earlier we may use Prepared Statement or callable statement according
to the requirement
STEP 4: Execute the Statement
In order to execute the query, you have to obtain the ResultSet object similar to
Record Set in Visual Basic and call the executeQuery() method of the Statement
interface. You have to pass a SQL Query like select * from students as a parameter to
the executeQuery() method. Actually, the RecordSet object contains both the data
returned by the query and the methods for data retrieval. The code for the above step
looks like this:
Record Set in Visual Basic and call the executeQuery() method of the Statement
interface. You have to pass a SQL Query like select * from students as a parameter to
the executeQuery() method. Actually, the RecordSet object contains both the data
returned by the query and the methods for data retrieval. The code for the above step
looks like this:
ResultSet rs = stmt.executeQuery(“select * from student”);
If you want to select only the name field you have to issue a SQL Syntax like
Select Name from Student
Select Name from Student
The executeUpdate() method is called whenever there is a delete or an update
operation.
operation.
STEP 5: Navigation or Looping through the ResultSet
The ResultSet object contains rows of data that is parsed using the next() method like
rs.next(). We use the getXXX() like, (getInt to retrieve Integer fields and getString
for String fields) method of the appropriate type to retrieve the value in each field.
If the first field in each row of ResultSet is Name (Stores String value), then getString
method is used. Similarly, if the Second field in each row stores int type, then getInt()
method is used like:
rs.next(). We use the getXXX() like, (getInt to retrieve Integer fields and getString
for String fields) method of the appropriate type to retrieve the value in each field.
If the first field in each row of ResultSet is Name (Stores String value), then getString
method is used. Similarly, if the Second field in each row stores int type, then getInt()
method is used like:
System.out.println(rs.getInt(“ID”));
STEP 6: Close the Connection and Statement Objects
After performing all the above steps, you must close the Connection, statement and
Resultset Objects appropriately by calling the close() method. For example, in our
above code we will close the object as:
Resultset Objects appropriately by calling the close() method. For example, in our
above code we will close the object as:
ResultSet object with
rs.close();
and statement object with
stmt.close();
Connection object with
conn.close();
No comments:
Post a Comment