Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. package com.luv2code.web.jdbc;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import javax.sql.DataSource;
  10.  
  11. public class StudentDbUtil {
  12. private DataSource dataSource;
  13. public StudentDbUtil(DataSource theDataSource) {
  14. dataSource=theDataSource;
  15. }
  16. public List<Student> getStudents() throws Exception{
  17. List<Student> students=new ArrayList<>();
  18. Connection myConn=null;
  19. Statement myStmt=null;
  20. ResultSet myRs=null;
  21. try {
  22. // get a connection
  23. myConn=dataSource.getConnection();
  24.  
  25. // create sql statement
  26. String sql="select * from student order by last_name";
  27. myStmt=myConn.createStatement();
  28. //execute query
  29. myRs=myStmt.executeQuery(sql);
  30. //process result set
  31. while(myRs.next()) {
  32. //retreive data from result set row
  33. int id=myRs.getInt("id");
  34. String firstName=myRs.getString("first_name");
  35. String lastName=myRs.getString("last_name");
  36. String email=myRs.getString("email");
  37.  
  38. //creaate new student object
  39. Student tempStudent=new Student(id,firstName,lastName,email);
  40.  
  41. //add it to thelist of student
  42. students.add(tempStudent);
  43. }
  44.  
  45. return students;
  46.  
  47. }
  48. finally {
  49. //close jdbc object
  50. close(myConn,myStmt,myRs);
  51. }
  52. }
  53. private void close(Connection myConn, Statement myStmt, ResultSet myRs) {
  54. // TODO Auto-generated method stub
  55. try {
  56. if(myRs!=null) {
  57. myRs.close();
  58. }
  59. if(myStmt!=null) {
  60. myStmt.close();
  61. }
  62. if(myConn!=null) {
  63. myConn.close();// doesnot really close it..just puts back in connection
  64. }
  65.  
  66. }
  67. catch(Exception exc) {
  68. exc.printStackTrace();
  69. }
  70.  
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement