Advertisement
lemansky

Untitled

Nov 10th, 2020
590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.55 KB | None | 0 0
  1. package app;
  2.  
  3. import java.sql.*;
  4. import java.util.*;
  5. /**
  6.  *
  7.  * @author sqlitetutorial.net
  8.  */
  9. public class Connect {
  10.      /**
  11.      * Connect to a sample database
  12.      */
  13.     public static ArrayList<String> connect() {
  14.         ArrayList<String> data = new ArrayList<String>();
  15.         Connection conn = null;
  16.         try {
  17.             // db parameters
  18.             String url = "jdbc:sqlite:chinook.db";
  19.             // create a connection to the database
  20.             conn = DriverManager.getConnection(url);
  21.            
  22.             System.out.println("Connection to SQLite has been established.");
  23.            
  24.             String sql = "SELECT FirstName, LastName FROM employees";
  25.             try (Connection openConn = conn;
  26.                 Statement stmt  = openConn.createStatement();
  27.                 ResultSet rs    = stmt.executeQuery(sql)){
  28.  
  29.                 // loop through the result set
  30.                 while (rs.next()) {
  31.                     data.add(rs.getString("FirstName") + " " +
  32.                                        rs.getString("LastName"));
  33.                 }
  34.             } catch (SQLException e) {
  35.                 System.out.println(e.getMessage());
  36.             }
  37.  
  38.         } catch (SQLException e) {
  39.             System.out.println(e.getMessage());
  40.         } finally {
  41.             try {
  42.                 if (conn != null) {
  43.                     conn.close();
  44.                 }
  45.             } catch (SQLException ex) {
  46.                 System.out.println(ex.getMessage());
  47.             }
  48.         }
  49.         return data;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement