Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String args[])
- {
- MYSQLDatabase database = new MYSQLDatabase();
- String host = "jdbc:mysql://localhost/LibraryDb";
- String username = "root";
- String password = "xxxxxxxx";
- database.connect(host,username,password);
- ResultSet result = database.query("select * from Books");
- while(result.next)
- {
- System.out.println("book found with title: "+ result.getString("title"));
- }
- result.close();
- }
- public class MYSQLDatabase {
- private Connection connection;
- public void connect(String connectionURL, String user, String password) throws SQLException, ClassNotFoundException
- {
- Class.forName("com.mysql.jdbc.Driver");
- if(connection != null && !connection.isClosed())
- return;
- connection = DriverManager.getConnection(connectionURL,user,password);
- }
- public void disconnect() throws SQLException
- {
- if(connection != null)
- connection.close();
- connection = null;
- }
- public ResultSet query(String query) throws SQLException
- {
- Statement sta = null;
- ResultSet result = null;
- CachedRowSet rowset = null;
- LogToFile.getLogger().log(Level.FINEST,"Trying to run query: " + query);
- try
- {
- if(!query.endsWith(";"))
- query += ";";
- sta = connection.createStatement();
- if(sta.execute(query))
- result = sta.getResultSet();
- if(result == null)
- return null;
- rowset = RowSetProvider.newFactory().createCachedRowSet();
- rowset.populate(result);
- }
- finally
- {
- if(sta != null)
- sta.close();
- }
- LogToFile.getLogger().log(Level.FINEST,"finished running query");
- return rowset;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement