Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. package javaClasses7;
  2.  
  3. import java.sql.*;
  4.  
  5. public class DB{
  6. private Connection conn = null;
  7. private Statement stmt = null;
  8. private ResultSet rs = null;
  9.  
  10. public void connect(){
  11. try {
  12. Class.forName("com.mysql.jdbc.Driver").newInstance();
  13. conn = DriverManager.getConnection("jdbc:mysql://mysql.agh.edu.pl/database",
  14. "database","password");
  15. } catch (SQLException ex) {
  16. // handle any errors
  17. System.out.println("SQLException: " + ex.getMessage());
  18. System.out.println("SQLState: " + ex.getSQLState());
  19. System.out.println("VendorError: " + ex.getErrorCode());
  20. }catch(Exception e){e.printStackTrace();}
  21. }
  22.  
  23. public void listAll(){
  24. try {
  25. connect();
  26. stmt = conn.createStatement();
  27.  
  28. // Wyciagamy wszystkie pola z tabeli
  29. rs = stmt.executeQuery("SELECT * FROM books");
  30.  
  31. while(rs.next()){
  32. String isbn = rs.getString(0);
  33. String title = rs.getString(1);
  34. String author = rs.getString(2);
  35. String year = rs.getString(3);
  36. System.out.println("ISBN: "+isbn+ "TITLE: "+title+ "AUTHOR: "+author+ "YEAR: "+year);
  37. }
  38. }catch (SQLException ex){
  39. // handle any errors
  40.  
  41. }finally {
  42. // zwalniamy zasoby, które nie będą potrzebne
  43. if (rs != null) {
  44. try {
  45. rs.close();
  46. } catch (SQLException sqlEx) { } // ignore
  47. rs = null;
  48. }
  49.  
  50. if (stmt != null) {
  51. try {
  52. stmt.close();
  53. } catch (SQLException sqlEx) { } // ignore
  54.  
  55. stmt = null;
  56. }
  57. }
  58. }
  59.  
  60. public static void main(String[] args){
  61. DB db = new DB();
  62. db.listAll();
  63. }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement