可能重复:
when to close Connection, Statement, PreparedStatement and ResultSet in JDBC良好做法:JDBC连接
我写了一个简单的包装了JDBC连接和它的作品,但我想用最好的实践,以提高它尽可能。它基本上具有如下方法:open()
,close()
,isOpened()
,select()
, insert()
, update()
, delete()
和batch()
。为了简单起见,我只会在这里发布前4种方法。
public class Query{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
//Database.open() returns a Connection ready to use
public void open (Database database) throws DatabaseException, SQLException{
if (!isOpened()){
con = database.open();
}
}
public void close() throws SQLException{
if (isOpened()){
if (ps != null) ps.close();
con.close();
con = null;
}
}
public boolean isOpened(){
return con != null;
}
//The query string is the query without the word "select" and can use placeholders (?)
//The args param it's just an array owith the values of this placeholders
public ResultSet select (String query, Object[] args) throws SQLException{
if (ps != null) ps.close();
if (isOpened()){
ps = con.prepareStatement ("select " + query);
if (args != null){
for (int i=0; i<args.length; i++){
ps.setObject (i+1, args[i]);
}
}
rs = ps.executeQuery();
}
return rs;
}
}
注:
- 相同的查询对象可重复使用,例如打开和关闭 它,并且再次打开之后。
- 我不关闭,每次查询的连接,我只是关闭 准备好的语句(这是正确的或我可以离开制 语句打开,因为Connection对象将关闭它?)
- 当我关闭
Connection
,所有的PreparedStatement
s和 他们的ResultSet
s也都关了吧?
用法:
Database database;
//Database initialization
Query query = new Query();
query.open (database);
ResultSet rs = query.select ("* from user where name=?", new String[]{ "MyName" });
doSomethingWithResult1 (rs);
//Connection is not closed here
ResultSet rs = query.select ("coordx from point where coordy=? and coordz=?", new Float[]{ 0.1, 0.2 });
doSomethingWithResult2 (rs);
query.close();
query.open (database);
ResultSet rs = query.select ("* from user where name=?", new String[]{ "MyName" });
doSomethingWithResult1 (rs);
//Connection is not closed here
ResultSet rs = query.select ("coordx from point where coordy=? and coordz=?", new Float[]{ 0.1, 0.2 });
doSomethingWithResult2 (rs);
query.close();
你觉得呢?我应该在每次查询后关闭并打开连接吗?在同一连接上的每个查询之后,我可以保留打开PreparedStatement吗?这是一个很好的设计?
关闭并重新打开每个查询的连接是一个坏主意。建立连接真的非常昂贵。 – bdares
然后,我可以离开打开PreparedStatement或者我应该关闭它的每个查询? –
您可以将所有内容保持打开状态,直到您实际使用数据库。关闭连接将追踪并关闭它产生的所有东西(语句,结果集)。 – bdares