gpt4 book ai didi

java - 良好做法 : JDBC Connection

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:29 27 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
when to close Connection, Statement, PreparedStatement and ResultSet in 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 和他们的 ResultSet 也关闭了,对吧?

用法:

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 状态吗?这是一个好的设计?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com