Connect to DB2 in Java – Solved
A solved example of how to connect to the db2 database in Java, run a query and retrieve its results. Then traverse through the returned result and output the results on the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public static void connectToDB() { //DB Address String hostName="192.168.1.1"; String port="50010"; //DB Info String dbName = "SCHOOLDB"; String dbUser="user"; String dbPassword="password"; String url = "jdbc:db2://"+ hostName+ ":" + port + "/" + dbName; try { Connection conn = DriverManager.getConnection(url,dbUser,dbPassword); java.sql.Statement stmt = conn.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT STUDENT_ID, FIRST_NAME, LAST_NAME VERSION_UPPER FROM STUDENTS"); while ( rs.next() ) { String sid = rs.getString("STUDENT_ID"); String fname= rs.getString("FIRST_NAME"); String lname= rs.getString("LAST_NAME"); System.out.println("Student ID = " + sid); System.out.println("First Name = " + fname); System.out.println("Last Name = " + lname); } conn.close(); } catch (Exception e) { System.err.println("Query failed to be executed. Exception: " +e.getMessage()); } } |
That’s it folks. Let me know if you have questions