Databases Reference
In-Depth Information
Example 5-3 Loading the Type 4 driver and getting connection to the database
Connection con = null;
Class.forName(“com.ibm.db2.jcc.DB2Driver”).newInstance();
con =
DriverManager.getConnection(“jdbc:db2://localhost:50000/sample”,”user”,
”password”);
In the case where multiple drivers are loaded, DriverManager is responsible for
making use of the appropriate driver to make a connection.
5.4.2 Manipulating data
After getting the connection, data can be selected, inserted, updated, or deleted
from the relational tables using SQL statements. JDBC driver implements two
interfaces Statement and PreparedStatement for this purpose. An object of any
of these classes is required for running an SQL statement.
Statement
An object of Statement (or class implementing the Statement interface) can be
used to execute the SQL statement which does not contain parameter markers.
An object can be created from the Connection object using createStatement
method.
Any number of statements can be created for a particular connection object.
Statement interface defines executeQuery and executeUpdate methods to
execute a query statement. The executeQuery method is used when the result
set is expected (for example, for the SELECT statement) as output of the query.
Alternatively, executeUpdate method is used for updating the database contents
(for example, INSERT, UPDATE, and DELETE statements). The executeQuery
method returns the ResultSet object, which represents a set of rows returned by
the SELECT query. This ResultSet object can be used to fetch the result row by
row. executeUpdate returns an integer value, which indicates the number of rows
updated, inserted, or deleted from the database based on the type of SQL
statement.
SELECT using Statement object
Example 5-4 contains a code snippet for the method getProducts from the
application code. The method select the product names from the CUSTOMER table
and stores them in the String array.
Example 5-4 SELECT using Statement object
String[] products=new String[10];
Search WWH ::




Custom Search