Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. package integration_tier;
  2. import com.mysql.jdbc.Driver;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.Statement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.PreparedStatement;
  9. import javax.swing.JOptionPane;
  10.  
  11. public class Connessione_Database {
  12.  
  13.     private static Connection conn = null; // connessione al database
  14.     static Statement statement; // per la query
  15.     static ResultSet resultSet;
  16.     static PreparedStatement prepStat;
  17.  
  18.     //nome del driver JDBC e URL del database
  19.  
  20.     static final String JDBC = "com.mysql.jdbc.Driver";
  21.     static final String DB_URL = "jdbc:mysql://localhost/carloan";
  22.  
  23.     public static void connessione(){
  24.  
  25.         String username = "root";
  26.         String password = "password";
  27.         conn = null;
  28.        
  29.         try {
  30.             Class.forName(JDBC); // può sollevare ClassNotFoundEcxeption.
  31.             conn = DriverManager.getConnection( DB_URL, username,password); //stabilisce la connessione
  32.         }
  33.         catch(ClassNotFoundException e){
  34.             e.printStackTrace();
  35.             JOptionPane.showMessageDialog(null, "Attenzione il driver del database non è stato trovato.");
  36.         }
  37.         catch(SQLException e){
  38.             e.printStackTrace();
  39.            
  40.             if(e.getErrorCode() == 1049){
  41.                 System.out.println("Attenzione! Database non presente.");
  42.                 JOptionPane.showMessageDialog(null, "Attenzione! Il database rischiesto non è presente.");
  43.             }
  44.             else{
  45.                 if(e.getErrorCode() == 1045){
  46.                    
  47.                     JOptionPane.showMessageDialog(null, "Attenzione username o password errati.");
  48.                 }
  49.                 else {
  50.                     JOptionPane.showMessageDialog(null,"Errore nella connessione al database! \n Contattare l'amministratore di sistema.\nIl sistema verrà chiuso ora.");
  51.                 }
  52.             }
  53.         }
  54.     }
  55.  
  56.  
  57.     // Pattern singleton: permette di mantenere un'unica istanza della connessione aperta.. così facendo
  58.     // non occorre aprire ogni volta una nuova connessione al DB per ogni singola azione su di esso..
  59.    
  60.     public static Connection getInstance(){
  61.         if (conn == null) {
  62.             connessione();
  63.         }
  64.         return conn;
  65.     }
  66.    
  67.    
  68.    
  69.    
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement