|
|
In Java Workshop, I 'll discuss JDBC,Servlet,System design,Servlet Design with all.here is the first section Statement.
About Exercise
In this exercise, you will develop an application using JDBC API to connect to a RDB, to send SQL query to the RDB, and to collect the results of a query. The flow of the application can be described in the following steps: The application executes a query to select department no(DEPTNUMB) and department name (DEPTNAME) from the organization table(org). It shows the result.
Database :sample Schema :db2admin Table :org User ID :db2admin Password :password DEPTNUMB DEPTNAME DIVISION LOCATION
10 Head Office 160 Corporate New York 15 New England 50 Eastern Boston 20 Mid Atlantic 10 Eastern Washington 38 South Atlantic 30 Eastern Atlanta 42 Greek Lakes 100 Midwest Chicago 51 Plains 140 Midwest Dallas 66 Pacific 270 Western San Francisco 84 Mountain 290 Western Denver
JPC_JDBCSample1.java //+++ (1)Import the JDBC package import [ 1 ];
class JPC_JDBCSample1 { public static void main(String args[]) { Connection con = null; Statement stmt = null; String sql = null; ResultSet rs = null;
try { // Load the driver Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
// Set JDBC URL in a variable // The URL is jdbc:db2:dbname String url = "jdbc:db2:sample";
//+++ (2) Connect to the DB specified by the JDBC URL //+++ with the user ID (db2admin) and the password (password) con = DriverManager.getConnection([ 2 ]);
//+++ (3) Create a Statement object stmt = con.[ 3 ];
//+++ (4) Specify a SQL statement sql = "[ 4 ]";
//+++ (5) Execute a query rs = stmt.[ 5 ];
// Retrieve the result from ResultSet and display it //+++ (6) Move the cursor down one row from its current position while (rs.[ 6 ]) {
//+++(7) Get a department no, specifying a column name short dno = [ 7 ];
//+++(8) Obtain a department name by specifying a column no String dname = [ 8 ]; System.out.print(" NO= " + dno); System.out.println(": " + dname ); }
} catch (ClassNotFoundException e){ e.printStackTrace(); } catch (SQLException e) { while (e != null) { System.err.println(e.getMessage()); e = e.getNextException(); } }finally{ try{ // Release resources rs.close(); stmt.close(); con.close(); }catch(SQLException e){ e.printStackTrace(); } } } }
Instructions
Open a command prompt window and change to the lab directory (d:/JPC/Ex/JDBC/). Compile your application.
javac JPC_JDBCSample1.java
Run your application.
java JPC_JDBCSample1
Demonstration >java JPC_JDBCSample1 NO= 10: Head Office NO= 15: New England NO= 20: Mid Atlantic NO= 38: South Atlantic NO= 42: Great Lakes NO= 51: Plains NO= 66: Pacific NO= 84: Mountain
the next topic is PrepareStatement,any question please click" 发表评论 " let me know tks.
|
|