Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //STEP 1. Import required packages
- import java.sql.*;
- public class FirstExample {
- // JDBC driver name and database URL
- //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
- //static final String DB_URL = "jdbc:mysql://localhost/mydb";
- static final String DB_URL ="jdbc:mysql://localhost/mydb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
- // Database credentials
- static final String USER = "root";
- static final String PASS = "mydb";
- public static void main(String[] args) {
- Connection conn = null;
- Statement stmt = null;
- try{
- //STEP 2: Register JDBC driver
- //Class.forName(JDBC_DRIVER);
- //STEP 3: Open a connection
- System.out.println("Connecting to database...");
- conn = DriverManager.getConnection(DB_URL,USER,PASS);
- //STEP 4: Execute a query
- System.out.println("Creating statement...");
- stmt = conn.createStatement();
- String sql;
- sql = "SELECT * FROM utilizadores ";
- ResultSet rs = stmt.executeQuery(sql);
- //STEP 5: Extract data from result set
- while(rs.next()){
- int id = rs.getInt("id_utilizador");
- System.out.print("ID: " + id);
- }
- //STEP 6: Clean-up environment
- rs.close(); stmt.close(); conn.close();
- }catch(SQLException se){
- se.printStackTrace();
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(stmt!=null) stmt.close();
- }catch(SQLException se2){}
- try{
- if(conn!=null) conn.close();
- }catch(SQLException se){ se.printStackTrace();}
- }//end try
- }//end main
- }//end FirstExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement