Java data access

Page 144

Chapter 7: Understanding JDBC Data Types

//Create Statement object stmt = conn.createStatement(); //Map the EMP_DATA UDT to the Employee class Map map = conn.getTypeMap(); map.put("EMP_DATA",Class.forName("Chapter7.Employee")); conn.setTypeMap(map); //Rebuild tables with the StructExample.createTables() method StructExample.createTables(stmt); //Retrieve the data System.out.println("Retrieving data from database...."); rs = stmt.executeQuery("SELECT * from Emp_Records"); //Custom class to hold EMP_DATA UDT on database Employee employee; //Loop through ResulSet to and display data System.out.println("Displaying data:"); while(rs.next()){ int empId = rs.getInt("EmpId"); //Notice the cast to Employee employee = (Employee)rs.getObject("Emp_Info"); System.out.print("Employee Id: " + empId + ", SSN: " + employee.SSN); System.out.print(", Name: " + employee.FirstName + " " + employee.LastName); System.out.println(", Yearly Salary: $" + employee.Salary + " Monthly Salary: " + employee.calcMonthlySalary()); } //Standard error handling } catch(SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end SqlDataEx

The output from Listing 7−5 is as follows: 132


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.