Guest User

Untitled

a guest
May 18th, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1.  
  2. import java.sql.*;
  3.  
  4. public class DBConnection {
  5.    
  6.     Connection conn;
  7.     ResultSet resultSet;
  8.    
  9.     public ResultSet getResults(){
  10.        
  11.         return resultSet;  
  12.     }
  13.    
  14.    public DBConnection(){ }
  15.    
  16.    
  17.    public void executeQuery(String query) {
  18.        
  19.         try{
  20.              Statement st  = conn.createStatement();
  21.              st.executeQuery(query);
  22.              resultSet = st.getResultSet();
  23.              
  24.         } catch(SQLException e  ) { System.err.println ("Error message: " + e.getMessage ()); }    
  25.    }
  26.    
  27.     public void executeUpdate(String query)  {
  28.        
  29.          try{
  30.               Statement st = conn.createStatement();
  31.               st.executeUpdate(query);  
  32.              
  33.         } catch(SQLException e  ) { System.err.println ("Error message: " + e.getMessage ()); }        
  34.     }
  35.    
  36.     public boolean createConnection(){
  37.        
  38.         try
  39.            {
  40.                String userName = "root";
  41.                String password = "secure";
  42.                String url = "jdbc:mysql://localhost/test";
  43.                Class.forName ("com.mysql.jdbc.Driver").newInstance ();
  44.                conn = DriverManager.getConnection (url, userName, password);
  45.                System.out.println ("Database connection established");
  46.                
  47.                return true;
  48.            }
  49.            catch (Exception e)
  50.            {
  51.                System.err.println ("Cannot connect to database server");
  52.                
  53.                return false;
  54.            }
  55.     }
  56.    
  57.     public boolean destroyConnection(){
  58.                
  59.                if (conn != null)
  60.                {
  61.                    try
  62.                    {
  63.                        conn.close ();
  64.                        System.out.println ("Database connection terminated");
  65.                        return true;
  66.                    }
  67.                    catch (Exception e) { /* ignore close errors */ }
  68.                }
  69.            
  70.        
  71.         return false;
  72.     }
  73.    
  74. }
Add Comment
Please, Sign In to add comment