目前,我加载以下自定义驱动程序(TestDriver.java),获取连接,创建Statement,执行查询,获取结果并关闭连接。我打开并关闭每个查询的连接。这是常见的做法还是有一种标准的方式来共享开放的连接?
public static void main(String[] args) {
Class.forName("com.sql.TestDriver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:test://8888/connectme", props);
Statement stmt = conn.createStatement;
ResultSet rs = stmt.executeQuery("select * from table");
//loop through rs and pull out needed data
conn.close();
}
public class TestDriver implements java.sql.Driver{
private final TestSchema schema;
private Properties props = null;
static {
try {
DriverManager.registerDriver(new TestDriver());
} catch (SQLException e) {
e.printStackTrace();
}
protected TestDriver() throws SQLException {
schema = TestSchemaFactory.getInstance().getDbSchemaFromFile(SCHEMA_FILE);
//loads in and parses a file containing tables, columns used for business logic
}
public Connection connect(String url, Properties info)
throws SQLException {
TestSqlConnection conn=null;
//connect logic here
return conn; //will return an instance of TestSqlConnection
}
@Override
public boolean jdbcCompliant() {
return false;
}
}
答案 0 :(得分:1)
是的,使用数据库连接池更常见。这将允许重复使用连接而无需开销或关闭/重新打开。这是DBCP的链接,DBCP是数据库连接池的一个实现:http://commons.apache.org/dbcp/
答案 1 :(得分:1)