Advertisement
Guest User

Untitled

a guest
Jul 12th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.68 KB | None | 0 0
  1. import java.sql.DriverManager;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.util.ArrayList;
  5. import java.sql.Connection;
  6.  
  7. public class DatabaseConnection {
  8.     private Connection connection;
  9.    
  10.     public DatabaseConnection() throws Exception {
  11.         // TODO Auto-generated constructor stub
  12.         getConnection();
  13.     }
  14.    
  15.     private Connection getConnection() throws Exception{
  16.         try{
  17.             String driver = "com.mysql.jdbc.Driver";
  18.             String url = "jdbc:mysql://localhost:3306/fibbo";
  19.             String username = "root";
  20.             String password = "";
  21.             Class.forName(driver);
  22.             Connection conn = DriverManager.getConnection(url,username,password);
  23.             System.out.println("Connected");
  24.             this.connection = conn;
  25.         } catch(Exception e){System.out.println(e);} return null;
  26.     }
  27.    
  28.     public void getNumbers() {
  29.         try {
  30.             PreparedStatement get = connection.prepareStatement("SELECT * FROM fibbo");
  31.             ResultSet result = get.executeQuery();
  32.             ArrayList<String> arrayList = new ArrayList<>();
  33.             while(result.next()) {
  34.                 arrayList.add(result.getString("id") + ": " + result.getString("number"));
  35.             }
  36.         }catch (Exception e) {
  37.             System.out.println(e);
  38.         }
  39.     }
  40.    
  41.     public void getNumber(int index) {
  42.         try {
  43.             PreparedStatement get = connection.prepareStatement("SELECT * FROM fibbo WHERE id='"+index+"'");
  44.             get.executeQuery();
  45.         }catch (Exception e) {
  46.             System.out.println(e);
  47.         }
  48.     }
  49.    
  50.     public void insertNumber(int index, int number) {
  51.         try {
  52.             PreparedStatement insert = connection.prepareStatement("INSERT INTO fibbo (id, number) VALUES ('" + index + "', '" + number +"')");
  53.             insert.executeUpdate();
  54.         }catch (Exception e) {
  55.             System.out.println(e);
  56.         }
  57.     }
  58.    
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement