Advertisement
Guest User

Untitled

a guest
Jan 18th, 2016
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1.  
  2. public static void main(String args[])
  3. {
  4.     MYSQLDatabase database = new MYSQLDatabase();
  5.     String host = "jdbc:mysql://localhost/LibraryDb";
  6.     String username = "root";
  7.     String password = "xxxxxxxx";
  8.     database.connect(host,username,password);
  9.    
  10.     ResultSet result = database.query("select * from Books");
  11.     while(result.next)
  12.     {
  13.         System.out.println("book found with title: "+ result.getString("title"));
  14.     }
  15.     result.close();
  16. }
  17.  
  18.  
  19. public class MYSQLDatabase {
  20.  
  21.     private Connection connection;
  22.  
  23.     public void connect(String connectionURL, String user, String password) throws SQLException, ClassNotFoundException
  24.     {
  25.         Class.forName("com.mysql.jdbc.Driver");
  26.         if(connection != null && !connection.isClosed())
  27.             return;
  28.         connection = DriverManager.getConnection(connectionURL,user,password);
  29.     }
  30.    
  31.     public void disconnect() throws SQLException
  32.     {
  33.         if(connection != null)
  34.             connection.close();
  35.         connection = null;
  36.     }
  37.    
  38.     public ResultSet query(String query) throws SQLException
  39.     {
  40.         Statement sta = null;
  41.         ResultSet result = null;
  42.         CachedRowSet rowset = null;
  43.         LogToFile.getLogger().log(Level.FINEST,"Trying to run query: " + query);
  44.         try
  45.         {
  46.             if(!query.endsWith(";"))
  47.                 query += ";";
  48.             sta = connection.createStatement();
  49.            
  50.             if(sta.execute(query))
  51.                 result = sta.getResultSet();
  52.            
  53.             if(result == null)
  54.                 return null;
  55.             rowset = RowSetProvider.newFactory().createCachedRowSet();
  56.             rowset.populate(result);
  57.         }
  58.         finally
  59.         {
  60.             if(sta != null)
  61.                 sta.close();
  62.         }
  63.         LogToFile.getLogger().log(Level.FINEST,"finished running query");
  64.         return rowset;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement