Java Reference
In-Depth Information
Suppose a data source named ExampleMDBDataSource has been created for an Access
database. The following statement creates a Connection object:
Connection connection = DriverManager.getConnection
( "jdbc:odbc:ExampleMDBDataSource" );
The databaseURL for a MySQL database specifies the host name and database name to
locate a database. For example, the following statement creates a Connection object for the
local MySQL database javabook with username scott and password tiger :
connect MySQL DB
Connection connection = DriverManager.getConnection
( "jdbc:mysql://localhost/javabook" , "scott" , "tiger" );
Recall that by default, MySQL contains two databases named mysql and test . Section 32.3.2,
Creating a Database, created a custom database named javabook . We will use javabook in
the examples.
The databaseURL for an Oracle database specifies the hostname , the port# where the
database listens for incoming connection requests, and the oracleDBSID database name to
locate a database. For example, the following statement creates a Connection object for the
Oracle database on liang.armstrong.edu with the username scott and password tiger :
connect Oracle DB
Connection connection = DriverManager.getConnection
( "jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl" ,
"scott" , "tiger" );
3. Creating statements.
If a Connection object can be envisioned as a cable linking your program to a database, an
object of Statement can be viewed as a cart that delivers SQL statements for execution by
the database and brings the result back to the program. Once a Connection object is created,
you can create statements for executing SQL statements as follows:
Statement statement = connection.createStatement();
4. Executing statements.
SQL data definition language (DDL) and update statements can be executed using
executeUpdate(String sql) , and an SQL query statement can be executed using
executeQuery(String sql) . The result of the query is returned in ResultSet . For
example, the following code executes the SQL statement create table Temp (col1
char(5), col2 char(5)) :
statement.executeUpdate
( "create table Temp (col1 char(5), col2 char(5))" );
This next code executes the SQL query select firstName, mi, lastName from
Student where lastName = 'Smith' :
// Select the columns from the Student table
ResultSet resultSet = statement.executeQuery
( "select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'" );
5. Processing ResultSet .
The ResultSet maintains a table whose current row can be retrieved. The initial row posi-
tion is null . You can use the next method to move to the next row and the various getter
methods to retrieve values from a current row. For example, the following code displays all
the results from the preceding SQL query.
// Iterate through the result and print the student names
while (resultSet.next())
 
 
Search WWH ::




Custom Search