Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.ResultSet;
  5.  
  6. /* Dane piwerwszych dwoch studentow
  7. ID: 1, name: Zenon, surname: Martyniuk, student_group: 2
  8. ID: 2, name: Bartłomiej, surname: Misiewicz, student_group: 4
  9. */
  10.  
  11. public class Main{
  12.  
  13. static final String DB_URL = "jdbc:mysql://ricky.heliohost.org/cackoa_database";
  14.  
  15. static final String USER = "cackoa_user";
  16. static final String PASS = "cackoa_password";
  17.  
  18. public static void main(String args[]){
  19.  
  20.  
  21. Connection polaczenie = null;
  22. java.sql.Statement stmt = null;
  23.  
  24. try{
  25. // Połączenie z bazą danych
  26.  
  27. System.out.println("Connecting to database...");
  28. polaczenie = DriverManager.getConnection(DB_URL,USER,PASS);
  29.  
  30. // Stworzenie zapytania oraz jego wykonanie
  31. System.out.println("Creating statement...");
  32. stmt = polaczenie.createStatement();
  33. String sql;
  34. sql = "SELECT * FROM student";
  35. ResultSet rs = stmt.executeQuery(sql);
  36.  
  37. // Ekstrakcja wyników
  38. while(rs.next()){
  39. //Retrieve by column name
  40. int id = rs.getInt("id");
  41. String name = rs.getString("name");
  42. String surname = rs.getString("surname");
  43. int student_group = rs.getInt("student_group");
  44.  
  45. //Wyświetlenie danych:
  46. System.out.print("ID: " + id);
  47. System.out.print(", name: " + name);
  48. System.out.print(", surname: " + surname);
  49. System.out.println(", student_group: " + student_group);
  50. }
  51. // Czyszczenie po sobie
  52. rs.close();
  53. stmt.close();
  54. polaczenie.close();
  55. }catch(SQLException se){
  56. //Errory JDBC
  57. se.printStackTrace();
  58. }catch(Exception e){
  59. e.printStackTrace();
  60. }finally{
  61. //finally block - by pozamykać resources
  62. try{
  63. if(stmt!=null)
  64. stmt.close();
  65. }catch(SQLException se2){
  66.  
  67. }// nothing we can do
  68. try{
  69. if(polaczenie!=null)
  70. polaczenie.close();
  71. }catch(SQLException se){
  72. se.printStackTrace();
  73. }//end finally try
  74. }//end try
  75. System.out.println("Koniec!");
  76.  
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement