以下是Main.java
:
package foo.sandbox.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
final String SQL = "select * from NVPAIR where name=?";
try (
Connection connection = DatabaseManager.getConnection();
PreparedStatement stmt = connection.prepareStatement(SQL);
DatabaseManager.PreparedStatementSetter<PreparedStatement> ignored = new DatabaseManager.PreparedStatementSetter<PreparedStatement>(stmt) {
@Override
public void init(PreparedStatement ps) throws SQLException {
ps.setString(1, "foo");
}
};
ResultSet rs = stmt.executeQuery()
) {
while (rs.next()) {
System.out.println(rs.getString("name") + "=" + rs.getString("value"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这里是DatabaseManager.java
package foo.sandbox.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Initialize script
* -----
* CREATE TABLE NVPAIR;
* ALTER TABLE PUBLIC.NVPAIR ADD value VARCHAR2 NULL;
* ALTER TABLE PUBLIC.NVPAIR ADD id int NOT NULL AUTO_INCREMENT;
* CREATE UNIQUE INDEX NVPAIR_id_uindex ON PUBLIC.NVPAIR (id);
* ALTER TABLE PUBLIC.NVPAIR ADD name VARCHAR2 NOT NULL;
* ALTER TABLE PUBLIC.NVPAIR ADD CONSTRAINT NVPAIR_name_pk PRIMARY KEY (name);
*
* INSERT INTO NVPAIR(name, value) VALUES('foo', 'foo-value');
* INSERT INTO NVPAIR(name, value) VALUES('bar', 'bar-value');
*/
public class DatabaseManager {
/**
* Class to allow PreparedStatement to initialize parmaters inside try-with-resource
* @param <T> extends Statement
*/
public static abstract class PreparedStatementSetter<T extends Statement> implements AutoCloseable {
public PreparedStatementSetter(PreparedStatement pstmt) throws SQLException {
init(pstmt);
}
@Override
public void close() throws Exception {
}
public abstract void init(PreparedStatement pstmt) throws SQLException;
}
/* Use local file for database */
private static final String JDBC_CONNECTION = "jdbc:h2:file:./db/sandbox_h2.db;MODE=PostgreSQL";
static {
try {
Class.forName("org.h2.Driver"); // Init H2 DB driver
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return Database connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(JDBC_CONNECTION, "su", "");
}
}
我使用H2数据库是为了简单起见,因为它是一个易于创建和测试的基于文件的数据库。
因此,所有工作和资源都按预期清理,但我只是觉得可能有更简洁的方法从try-with-resources块中设置PreparedStatement
参数(我不会这样做)想要使用嵌套的try / catch块,因为它们看起来很尴尬(&#39;)。也许在JDBC中已经存在一个帮助类就是这样,但是我找不到它。
最好使用lambda函数初始化PreparedStatement
,但它仍然需要分配一个AutoCloseable
对象,以便它可以在try-with-resources中。
答案 0 :(得分:7)
首先,您的PreparedStatementSetter
课程很尴尬:
请考虑以下界面(灵感来自同名的Spring interface)。
public interface PreparedStatementSetter {
void setValues(PreparedStatement ps) throws SQLException;
}
此界面定义了PreparedStatementSetter
应该做什么的合约:设置PreparedStatement
的值,仅此而已。
然后,最好在单个方法中创建PreparedStatement
的创建和初始化。请考虑在DatabaseManager
类中添加此内容:
public static PreparedStatement prepareStatement(Connection connection, String sql, PreparedStatementSetter setter) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql);
setter.setValues(ps);
return ps;
}
使用此静态方法,您可以编写:
try (
Connection connection = DatabaseManager.getConnection();
PreparedStatement stmt = DatabaseManager.prepareStatement(connection, SQL, ps -> ps.setString(1, "foo"));
ResultSet rs = stmt.executeQuery()
) {
// rest of code
}
注意PreparedStatementSetter
如何用lambda表达式写在这里。这是使用接口而不是抽象类的优势之一:在这种情况下它实际上是一个功能接口(因为有一个抽象方法),因此可以写成lambda。
答案 1 :(得分:2)
从@Tunaki的回答中延伸出来,也可以考虑 try-with-resources 和rs.executeQuery()
,以便DatabaseManager
为您处理所有这些问题。只询问SQL,PreparedStatementSetter
和ResultSet
处理程序。
这样可以避免在您进行查询的任何地方重复此操作。实际的API将取决于您的使用情况 - 例如你会使用相同的连接进行多次查询吗?
假设你愿意,我提出以下建议:
public class DatabaseManager implements AutoCloseable {
/* Use local file for database */
private static final String JDBC_CONNECTION = "jdbc:h2:file:./db/sandbox_h2.db;MODE=PostgreSQL";
static {
try {
Class.forName("org.h2.Driver"); // Init H2 DB driver
} catch (Exception e) {
e.printStackTrace();
}
}
private final Connection connection;
private DatabaseManager() throws SQLException {
this.connection = getConnection();
}
@Override
public void close() throws SQLException {
connection.close();
}
public interface PreparedStatementSetter {
void setValues(PreparedStatement ps) throws SQLException;
}
public interface Work {
void doWork(DatabaseManager manager) throws SQLException;
}
public interface ResultSetHandler {
void process(ResultSet resultSet) throws SQLException;
}
/**
* @return Database connection
* @throws SQLException
*/
private static Connection getConnection() throws SQLException {
return DriverManager.getConnection(JDBC_CONNECTION, "su", "");
}
private PreparedStatement prepareStatement(String sql, PreparedStatementSetter setter) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql);
setter.setValues(ps);
return ps;
}
public static void executeWork(Work work) throws SQLException {
try (DatabaseManager dm = new DatabaseManager()) {
work.doWork(dm);
}
}
public void executeQuery(String sql, PreparedStatementSetter setter, ResultSetHandler handler) throws SQLException {
try (PreparedStatement ps = prepareStatement(sql, setter);
ResultSet rs = ps.executeQuery()) {
handler.process(rs);
}
}
}
它将连接包装为DatabaseManager
的实例字段,由于其AutoCloseable
的实现,它将处理连接的生命周期。
它还定义了2个新的功能接口(除了@Tinaki的PreparedStatementSetter
):
Work
通过DatabaseManager
静态方法executeWork
有关的一些工作
ResultSetHandler
定义了在通过新的ResultSet
实例方法执行查询时必须如何处理executeQuery
。可以按如下方式使用:
final String SQL = "select * from NVPAIR where name=?";
try {
DatabaseManager.executeWork(dm -> {
dm.executeQuery(SQL, ps -> ps.setString(1, "foo"), rs -> {
while (rs.next()) {
System.out.println(rs.getString("name") + "=" + rs.getString("value"));
}
});
// other queries are possible here
});
} catch (Exception e) {
e.printStackTrace();
}
如您所见,您不必担心任何资源处理 更多。
我将SQLException
处理放在api之外,因为你可能想让它传播。
此解决方案的灵感来自Design Patterns in the Light of Lambda Expressions by Subramaniam。
答案 2 :(得分:0)
我找到了另一种方法,可能对人们有所帮助:
PreparedStatementExecutor.java:
/**
* Execute PreparedStatement to generate ResultSet
*/
public interface PreparedStatementExecutor {
ResultSet execute(PreparedStatement pstmt) throws SQLException;
}
PreparedStatementSetter.java:
/**
* Lambda interface to help initialize PreparedStatement
*/
public interface PreparedStatementSetter {
void prepare(PreparedStatement pstmt) throws SQLException;
}
JdbcTriple.java:
/**
* Contains DB objects that close when done
*/
public class JdbcTriple implements AutoCloseable {
Connection connection;
PreparedStatement preparedStatement;
ResultSet resultSet;
/**
* Create Connection/PreparedStatement/ResultSet
*
* @param sql String SQL
* @param setter Setter for PreparedStatement
* @return JdbcTriple
* @throws SQLException
*/
public static JdbcTriple create(String sql, PreparedStatementSetter setter) throws SQLException {
JdbcTriple triple = new JdbcTriple();
triple.connection = DatabaseManager.getConnection();
triple.preparedStatement = DatabaseManager.prepareStatement(triple.connection, sql, setter);
triple.resultSet = triple.preparedStatement.executeQuery();
return triple;
}
public Connection getConnection() {
return connection;
}
public PreparedStatement getPreparedStatement() {
return preparedStatement;
}
public ResultSet getResultSet() {
return resultSet;
}
@Override
public void close() throws Exception {
if (resultSet != null)
resultSet.close();
if (preparedStatement != null)
preparedStatement.close();
if (connection != null)
connection.close();
}
}
DatabaseManager.java:
/**
* Initialize script
* -----
* CREATE TABLE NVPAIR;
* ALTER TABLE PUBLIC.NVPAIR ADD value VARCHAR2 NULL;
* ALTER TABLE PUBLIC.NVPAIR ADD id int NOT NULL AUTO_INCREMENT;
* CREATE UNIQUE INDEX NVPAIR_id_uindex ON PUBLIC.NVPAIR (id);
* ALTER TABLE PUBLIC.NVPAIR ADD name VARCHAR2 NOT NULL;
* ALTER TABLE PUBLIC.NVPAIR ADD CONSTRAINT NVPAIR_name_pk PRIMARY KEY (name);
*
* INSERT INTO NVPAIR(name, value) VALUES('foo', 'foo-value');
* INSERT INTO NVPAIR(name, value) VALUES('bar', 'bar-value');
*/
public class DatabaseManager {
/* Use local file for database */
private static final String JDBC_CONNECTION = "jdbc:h2:file:./db/sandbox_h2.db;MODE=PostgreSQL";
static {
try {
Class.forName("org.h2.Driver"); // Init H2 DB driver
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return Database connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(JDBC_CONNECTION, "su", "");
}
/** Prepare statement */
public static PreparedStatement prepareStatement(Connection conn, String SQL, PreparedStatementSetter setter) throws SQLException {
PreparedStatement pstmt = conn.prepareStatement(SQL);
setter.prepare(pstmt);
return pstmt;
}
/** Execute statement */
public static ResultSet executeStatement(PreparedStatement pstmt, PreparedStatementExecutor executor) throws SQLException {
return executor.execute(pstmt);
}
}
Main.java:
public class Main {
public static void main(String[] args) {
final String SQL = "select * from NVPAIR where name=?";
try (
JdbcTriple triple = JdbcTriple.create(SQL, pstmt -> { pstmt.setString(1, "foo"); })
){
while (triple.getResultSet().next()) {
System.out.println(triple.getResultSet().getString("name") + "=" + triple.getResultSet().getString("value"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
虽然这不会处理您可能需要从插入或事务中返回ID的情况,但它确实提供了一种快速方法来运行查询,设置参数并获取ResultSet,在我的情况下,它是大量数据库代码。