Advertisement
Guest User

Untitled

a guest
Nov 12th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. //STEP 1. Import required packages
  2. import java.sql.*;
  3.  
  4. public class FirstExample {
  5. // JDBC driver name and database URL
  6. //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  7. //static final String DB_URL = "jdbc:mysql://localhost/mydb";
  8. static final String DB_URL ="jdbc:mysql://localhost/mydb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
  9. // Database credentials
  10. static final String USER = "root";
  11. static final String PASS = "mydb";
  12. public static void main(String[] args) {
  13. Connection conn = null;
  14. Statement stmt = null;
  15. try{
  16. //STEP 2: Register JDBC driver
  17. //Class.forName(JDBC_DRIVER);
  18. //STEP 3: Open a connection
  19. System.out.println("Connecting to database...");
  20. conn = DriverManager.getConnection(DB_URL,USER,PASS);
  21. //STEP 4: Execute a query
  22. System.out.println("Creating statement...");
  23. stmt = conn.createStatement();
  24. String sql;
  25. sql = "SELECT * FROM utilizadores ";
  26. ResultSet rs = stmt.executeQuery(sql);
  27. //STEP 5: Extract data from result set
  28. while(rs.next()){
  29. int id = rs.getInt("id_utilizador");
  30. System.out.print("ID: " + id);
  31.  
  32. }
  33. //STEP 6: Clean-up environment
  34. rs.close(); stmt.close(); conn.close();
  35. }catch(SQLException se){
  36. se.printStackTrace();
  37. }catch(Exception e){
  38. e.printStackTrace();
  39. }finally{
  40. try{
  41. if(stmt!=null) stmt.close();
  42. }catch(SQLException se2){}
  43. try{
  44. if(conn!=null) conn.close();
  45. }catch(SQLException se){ se.printStackTrace();}
  46. }//end try
  47. }//end main
  48. }//end FirstExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement