Advertisement
TeslaCoilGirl

Java SQLite

Jun 29th, 2020
1,095
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.44 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.ArrayList;
  3. import java.util.NoSuchElementException;
  4. import java.util.Scanner;
  5. public class SQLStuff {
  6.     public static void main(String[] args) {
  7.         CreateDatabase db = new CreateDatabase();
  8.         Boolean continuation = true;
  9.         Connection c = null;
  10.         Statement stmt = null;
  11.        
  12.         //db.databaseCreate(c);
  13.         //db.tableCreate(c, stmt);
  14.        
  15.         Scanner sc = new Scanner(System.in);
  16.         while(continuation) {
  17.             System.out.println("What operation do you want to execute?\nINSERT PERSON, PRINT PERSON, PRINT ALL, UPDATE PERSON, DELETE PERSON");
  18.             String userIn = sc.nextLine();
  19.             switch(userIn) {
  20.             case "INSERT PERSON":
  21.                 db.insertPerson(c, stmt);
  22.                 break;
  23.             case "PRINT PERSON":
  24.                 db.printPeople(db.selectPerson(c, stmt));
  25.                 break;
  26.             case "PRINT ALL":
  27.                 db.printPeople(db.findAllPeople(c, stmt));
  28.                 break;
  29.             case "UPDATE PERSON":
  30.                 db.updatePerson(c, stmt);
  31.                 break;
  32.             case "DELETE PERSON":
  33.                 db.deletePerson(c, stmt);
  34.                 break;
  35.             default:
  36.                 System.out.println("Unrecognized command.");
  37.             }
  38.             System.out.println("Continue? Y/N");
  39.             String ct = sc.nextLine();
  40.             if(ct.equals("Y")) {
  41.                 continuation = true;
  42.             }
  43.             else {
  44.                 continuation = false;
  45.             }
  46.         }
  47.         System.out.println("Exited.");
  48. }
  49.  
  50.  
  51. }
  52. class CreateDatabase {
  53.     public void databaseCreate(Connection c) {
  54.         try {
  55.             Class.forName("org.sqlite.JDBC");
  56.             c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  57.         }
  58.         catch (Exception e) {
  59.             System.err.println(e.getClass().getName() + ": " + e.getMessage());
  60.             System.exit(0);
  61.         }
  62.         System.out.println("Opened database successfully.");
  63.     }
  64.     public void tableCreate(Connection c, Statement stmt) {
  65.         try {
  66.             Class.forName("org.sqlite.JDBC");
  67.             c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  68.             System.out.println("Database retrieved successfully.");
  69.            
  70.             stmt = c.createStatement();
  71.             String sql = "CREATE TABLE PERSON " +
  72.                          "(ID INT PRIMARY KEY   NOT NULL," +
  73.                          "FIRSTNAME       TEXT  NOT NULL," +
  74.                          "LASTNAME        TEXT  NOT NULL," +
  75.                          "AGE             INT   NOT NULL," +
  76.                          "SSN             REAL  NOT NULL," +
  77.                          "CC              REAL  NOT NULL)";
  78.             stmt.executeUpdate(sql);
  79.             stmt.close();
  80.             c.close();
  81.         }
  82.         catch (Exception e) {
  83.             System.err.println(e.getClass().getName() + ": " + e.getMessage());
  84.             System.exit(0);
  85.         }
  86.         System.out.println("Table created successfully.");
  87.     }
  88.     public void infoCreate(Connection c, Statement stmt) {
  89.         try {
  90.             Person p = new Person(2,"Bob","Thompson",27,201234092,440019193);
  91.             Class.forName("org.sqlite.JDBC");
  92.             c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  93.             c.setAutoCommit(false);
  94.             System.out.println("Accessed database successfully.");
  95.             stmt = c.createStatement();
  96.             String sql = "INSERT INTO PERSON (ID,FIRSTNAME,LASTNAME,AGE,SSN,CC) "+
  97.                          p.buildSQL();
  98.             stmt.executeUpdate(sql);
  99.             stmt.close();
  100.             c.commit();
  101.             c.close();
  102.         }
  103.         catch(Exception e) {
  104.             System.err.println(e.getClass().getName()+ ": "+e.getMessage());
  105.             System.exit(0);
  106.         }
  107.         System.out.println("Records created successfully.");
  108.     }
  109.     public void insertPerson(Connection c, Statement stmt) {
  110.         Scanner sc = new Scanner(System.in);
  111.         System.out.println("Enter id start: ");
  112.         int id = sc.nextInt();
  113.         Boolean entry = true;
  114.         while (entry) {
  115.             Person p = new Person();
  116.             p.buildPerson(id);
  117.             try {
  118.                 Class.forName("org.sqlite.JDBC");
  119.                 c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  120.                 c.setAutoCommit(false);
  121.                 //System.out.println("Accessed database successfully.");
  122.                 stmt = c.createStatement();
  123.                 String sql = "INSERT INTO PERSON (ID,FIRSTNAME,LASTNAME,AGE,SSN,CC) "+
  124.                              p.buildSQL();
  125.                 stmt.executeUpdate(sql);
  126.                 stmt.close();
  127.                 c.commit();
  128.                 c.close();
  129.             }
  130.             catch (SQLException e) {
  131.                 System.out.println("Value already exists. Enter different ID.");
  132.             }
  133.             catch(Exception e) {
  134.                 System.err.println(e.getClass().getName()+ ": "+e.getMessage());
  135.                 System.exit(0);
  136.             }
  137.             System.out.println("Records created successfully.");
  138.             id++;
  139.             System.out.println("Add more records? 0/1 ");
  140.  
  141.             int val = sc.nextInt();
  142.             if(val == 1) {
  143.                 entry = true;
  144.             } else {
  145.                 entry = false;
  146.             }
  147.         }
  148.     }
  149.     public ArrayList<Person> findAllPeople(Connection c, Statement stmt) {
  150.         ArrayList<Person> people = new ArrayList<Person>();
  151.         try {
  152.             Class.forName("org.sqlite.JDBC");
  153.             c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  154.             c.setAutoCommit(false);
  155.             System.out.println("Opened database successfully.");
  156.            
  157.             stmt = c.createStatement();
  158.             ResultSet rs = stmt.executeQuery("SELECT * FROM PERSON;");
  159.            
  160.             while(rs.next()) {
  161.                 int id = rs.getInt("ID");
  162.                 String firstName = rs.getString("FIRSTNAME");
  163.                 String lastName = rs.getString("LASTNAME");
  164.                 int age = rs.getInt("AGE");
  165.                 long ssn = rs.getLong("SSN");
  166.                 long cc = rs.getLong("CC");
  167.                 Person p = new Person(id,firstName,lastName,age,ssn,cc);
  168.                 people.add(p);
  169.             }
  170.             rs.close();
  171.             stmt.close();
  172.             c.close();
  173.         }
  174.         catch(Exception e) {
  175.             System.err.println(e.getClass().getName()+ ": " + e.getMessage());
  176.             System.exit(0);
  177.         }
  178.         System.out.println("Operation done successfully.");
  179.         return people;
  180.     }
  181.     public void printPeople(ArrayList<Person> people) {
  182.         for(Person person : people) {
  183.             System.out.println("ID: "+ person.id);
  184.             System.out.println("First Name: " + person.firstName);
  185.             System.out.println("Last Name: "+person.lastName);
  186.             System.out.println("Age: " + person.age);
  187.             System.out.println("SSN: "+person.ssn);
  188.             System.out.println("Credit Card: "+person.cc+"\n");
  189.         }
  190.     }
  191.     public ArrayList<Person> selectPerson(Connection c, Statement stmt) {
  192.         Scanner sc = new Scanner(System.in);
  193.         System.out.println("Enter unique person ID: ");
  194.         int userid=sc.nextInt();
  195.         ArrayList<Person> people = new ArrayList<Person>();
  196.         try {
  197.             Class.forName("org.sqlite.JDBC");
  198.             c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  199.             c.setAutoCommit(false);
  200.             System.out.println("Opened database successfully.");
  201.            
  202.             stmt = c.createStatement();
  203.             ResultSet rs = stmt.executeQuery("SELECT * FROM PERSON WHERE ID="+userid+";");
  204.            
  205.    
  206.             int id = rs.getInt("ID");
  207.             String firstName = rs.getString("FIRSTNAME");
  208.             String lastName = rs.getString("LASTNAME");
  209.             int age = rs.getInt("AGE");
  210.             long ssn = rs.getLong("SSN");
  211.             long cc = rs.getLong("CC");
  212.             Person p = new Person(id,firstName,lastName,age,ssn,cc);
  213.             people.add(p);
  214.  
  215.             rs.close();
  216.             stmt.close();
  217.             c.close();
  218.         }
  219.         catch (SQLException e) {
  220.             System.out.println("Out of bounds.");
  221.         }
  222.         catch(Exception e) {
  223.             System.err.println(e.getClass().getName()+ ": " + e.getMessage());
  224.             System.exit(0);
  225.         }
  226.        
  227.         System.out.println("Operation done successfully.");
  228.         return people;
  229.     }
  230.     public void updatePerson(Connection c, Statement stmt) {
  231.         try {
  232.               Class.forName("org.sqlite.JDBC");
  233.               c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  234.               c.setAutoCommit(false);
  235.               System.out.println("Opened database successfully");
  236.  
  237.               stmt = c.createStatement();
  238.              
  239.               Scanner sc = new Scanner(System.in);
  240.               System.out.println("Update which ID? ");
  241.               int userid = sc.nextInt();
  242.               System.out.println("Update which value? ");
  243.               String userval = sc.next();
  244.               System.out.println("Enter new value: ");
  245.               String newVal = sc.next();      
  246.               String sql;
  247.               switch(userval) {
  248.                 case "FIRSTNAME":
  249.                     sql = "UPDATE PERSON set "+userval+" = '"+newVal+"' where ID="+userid+";";
  250.                     break;
  251.                 case "LASTNAME":
  252.                     sql = "UPDATE PERSON set "+userval+" = '"+newVal+"' where ID="+userid+";";
  253.                     break;
  254.                 default:
  255.                     sql = "UPDATE PERSON set "+userval+" = "+newVal+" where ID="+userid+";";
  256.                     break;
  257.               }
  258.               stmt.executeUpdate(sql);
  259.               c.commit();
  260.         }
  261.         catch(SQLException e) {
  262.             System.out.println("Unrecognized command. Be sure to type it LIKETHIS.");
  263.         }
  264.          catch ( Exception e ) {
  265.               System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  266.               System.exit(0);
  267.            }
  268.             System.out.println("Operation done successfully");
  269.     }
  270.    
  271.     public void deletePerson(Connection c, Statement stmt) {
  272.         Scanner sc = new Scanner(System.in);
  273.         System.out.println("Enter user first name to delete: ");
  274.         String userfirst = sc.nextLine();
  275.         System.out.println("Enter user last name to delete: ");
  276.         String userlast = sc.nextLine();
  277.        
  278.         try {
  279.              Class.forName("org.sqlite.JDBC");
  280.              c = DriverManager.getConnection("jdbc:sqlite:SQLtest.db");
  281.              c.setAutoCommit(false);
  282.              System.out.println("Opened database successfully");
  283.  
  284.              stmt = c.createStatement();
  285.              String sql = "DELETE from PERSON where FIRSTNAME='"+userfirst+"' AND LASTNAME='"+userlast+"' where EXISTS;";
  286.              stmt.executeUpdate(sql);
  287.              c.commit();
  288.         }
  289.         catch (SQLException e) {
  290.             System.out.println("No such person exists.");
  291.         }
  292.         catch ( Exception e ) {
  293.              System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  294.              System.exit(0);
  295.          }
  296.          System.out.println("Operation done successfully");
  297.     }
  298. }
  299.  
  300.  
  301. class Person {
  302.     int id;
  303.     String firstName;
  304.     String lastName;
  305.     int age;
  306.     long ssn;
  307.     long cc;
  308.    
  309.     Person(int id, String firstName, String lastName,int age,long ssn,long cc){
  310.         this.id = id;
  311.         this.firstName = firstName;
  312.         this.lastName = lastName;
  313.         this.age = age;
  314.         this.ssn = ssn;
  315.         this.cc = cc;
  316.     }
  317.    
  318.     Person(){
  319.        
  320.     }
  321.     public void buildPerson(int id) {
  322.         this.id = id;
  323.         Scanner sc = new Scanner(System.in);
  324.         System.out.println("Enter first name: ");
  325.         this.firstName = sc.nextLine();
  326.         System.out.println("Enter last name: ");
  327.         this.lastName = sc.nextLine();
  328.         System.out.println("Enter age: ");
  329.         this.age = sc.nextInt();
  330.         System.out.println("Enter SSN: ");
  331.         this.ssn = sc.nextLong();
  332.         System.out.println("Enter credit card number: ");
  333.         this.cc = sc.nextLong();
  334.         System.out.println("Person info added.");
  335.     }
  336.     public String buildSQL() {
  337.     StringBuilder str = new StringBuilder();
  338.     str.append("VALUES (");
  339.     str.append(this.id);
  340.     str.append(",'");
  341.     str.append(this.firstName);
  342.     str.append("','");
  343.     str.append(this.lastName);
  344.     str.append("',");
  345.     str.append(this.age);
  346.     str.append(",");
  347.     str.append(this.ssn);
  348.     str.append(",");
  349.     str.append(this.cc);
  350.     str.append(");");
  351.     return str.toString(); 
  352.     }
  353. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement