Last active
March 6, 2016 02:33
-
-
Save johnllao/6827405193438420226b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.hello.tomcat.data; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Database { | |
private final String connectionUrl; | |
private Connection connection = null; | |
public static Database create(String connectionUrl) throws ClassNotFoundException { | |
return new Database(connectionUrl); | |
} | |
public Database(String connectionUrl) throws ClassNotFoundException { | |
Class.forName(org.sqlite.JDBC.class.getName()); | |
this.connectionUrl = connectionUrl; | |
} | |
public Database connect() throws SQLException { | |
this.connection = DriverManager.getConnection(this.connectionUrl); | |
return this; | |
} | |
public Database close() throws SQLException { | |
if (this.connection != null && !this.connection.isClosed()) | |
this.connection.close(); | |
return this; | |
} | |
public <T> List<T> query (String sql, Factory<T> factory) throws Exception { | |
final Statement statement = this.connection.createStatement(); | |
final ResultSet resultSet = statement.executeQuery(sql); | |
final List<T> list = new ArrayList<T>(); | |
while(resultSet.next()) { | |
list.add(factory.create(resultSet)); | |
} | |
return list; | |
} | |
public void execute(String sql) throws SQLException { | |
final Statement statement = this.connection.createStatement(); | |
statement.execute(sql); | |
statement.close(); | |
} | |
public void execute(String... sql) throws SQLException { | |
final Statement statement = this.connection.createStatement(); | |
for(String s : sql) { | |
statement.addBatch(s); | |
} | |
statement.executeBatch(); | |
statement.close(); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.hello.tomcat.data; | |
import java.sql.ResultSet; | |
public interface Factory<T> { | |
public T create(ResultSet resultSet) throws Exception; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment