Java Reference
In-Depth Information
Class.forName("com.mysql.jdbc.Driver") dynamically loads the MySQL database driver. It is embed-
ded in a try catch block in case exceptions occur. The URL variable contains the location of the database
schema, and the username and password variables store the logon credentials. The query variable is a string
containing the SQL query you want to execute. Note that it is a join query, whereby the Employee and
Department tables are joined. The statement connection = DriverManager.getConnection(url, user-
name, password) establishes a connection to the MySQL database by creating a connection object using
the logon information. In JDBC, all SQL statements are executed within the context of a connection object.
A Java program can have multiple connections to different databases. The statement stmt = connection.
createStatement() creates a statement object for sending SQL statements to the MySQL database. The
statement ResultSet rs = stmt.executeQuery(query); executes the query and stores the result thereof
into the rs object. It's important to note that in JDBC, all SQL queries are compiled and processed at
runtime. The rs resultset object contains a cursor pointing to a particular row of data in the result. Initially,
it is put before the first row and can be moved using the method next . The latter returns false when there
are no more rows in the resultset. The while loop, which follows, now navigates through the results of the
resultset. The statement System.out.print(rs.getString(1)); then retrieves the first element ( E.Name )
of the row where the cursor is positioned. The statement System.out.print(" "); then adds some extra
space and is followed by the statement System.out.println(rs.getString(2)); which retrieves the sec-
ond element (i.e. D.DName ) of the row where the cursor is positioned and adds a line break. To conclude the
program, the statement and connection objects are properly closed.
In the following example, you will use JDBC to access a MySQL database in combination with user-
provided input.
accessing a relational Database Using JDBC and User Input 
try it out
In this example, you will allow the user to provide input for the query in the JDBC program.
1.
Create a new class by right-clicking on the src folder in your Chapter9 project. Select New Class.
2.
In the Name field, enter the name of your class, JDBCExample2 . In the bottom portion of the New
Java Class window, there is a section that reads, “Which method stubs would you like to create?”
You may choose to check the box next to “ public static void main(String[] args) ” to
automatically create a main method.
3.
You should automatically have the basis for the class body shown here:
public class JDBCExample2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
4.
Adapt this class definition as follows:
import java.sql.*;
import java.util.*;
public class JDBCExample2 {
Search WWH ::




Custom Search