Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. public Student getStudent(int id) {
  2. Student stu = null;
  3. try{
  4. Class.forName("com.mysql.jdbc.Driver");
  5. Connection mySQLCon = DriverManager.getConnection("jdbc:mysql://localhost/company", "root", "1q2w3e");
  6.  
  7. PreparedStatement ps =
  8. mySQLCon.prepareStatement("select * from student where id=?");
  9. ps.setInt(1, id);
  10.  
  11. ResultSet rs = ps.executeQuery();
  12.  
  13. rs.next();
  14. return new Student(rs.getInt("id"), rs.getString("name"), rs.getString("lastname"));
  15.  
  16. }
  17. catch (Exception e) {
  18. e.printStackTrace();
  19.  
  20. }
  21. return null;
  22. }
  23.  
  24. public List<Student> getAllStudents() {
  25. List<Student> stus = new ArrayList<>();
  26. try{
  27. Class.forName("com.mysql.jdbc.Driver");
  28. Connection mySQLCon = DriverManager.getConnection("jdbc:mysql://localhost/company", "root", "1q2w3e");
  29.  
  30. PreparedStatement ps =
  31. mySQLCon.prepareStatement("select * from student");
  32.  
  33. ResultSet rs = ps.executeQuery();
  34.  
  35. while(rs.next())
  36. {
  37. Student s = new Student(rs.getInt("id"), rs.getString("name"), rs.getString("lastname"));
  38. stus.add(s);
  39. }
  40.  
  41.  
  42. }
  43. catch (Exception e) {
  44. e.printStackTrace();
  45.  
  46. }
  47. return stus;
  48.  
  49. }
  50.  
  51. public boolean addStudent(String name, String lastname) {
  52. try{
  53. Class.forName("com.mysql.jdbc.Driver");
  54. Connection mySQLCon = DriverManager.getConnection("jdbc:mysql://localhost/company", "root", "1q2w3e");
  55.  
  56. PreparedStatement ps =
  57. mySQLCon.prepareStatement("insert into student (name,lastname) values (?,?)");
  58. ps.setString(1, name);
  59. ps.setString(2, lastname);
  60. int result = ps.executeUpdate();
  61. if(result ==1)
  62. {
  63. return true;
  64. }
  65. else{
  66. return false;
  67. }
  68. }
  69. catch (Exception e) {
  70. e.printStackTrace();
  71.  
  72. }
  73. return false;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement