Advertisement
lemansky

Untitled

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