JAVA JDBC 重用连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15382913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA JDBC reusing connections
提问by user1582625
I have a Java program in which I am doing some JDBC for select queries. Will it be advisable to call testDataBase() each time which inturns calls DBConnection() each time or I should reuse one connection for all the queries. Thanks in advance.
我有一个 Java 程序,在其中我正在为选择查询执行一些 JDBC。是否建议每次调用 testDataBase() 每次调用 DBConnection() 或者我应该为所有查询重用一个连接。提前致谢。
private void testDataBase(String query){
Connection con = DBConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
rs = st.executeQuery(query);
boolean flag = true;
while (rs.next()) {
String resultString = "";
for(int i = 1; i <=rs.getMetaData().getColumnCount();i++){
resultString=resultString+" "+ rs.getString(i);
}
System.out.println(resultString);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private Connection DBConnection() {
final String method_name = "DBConnection";
Connection conn = null;
try{
Class.forName(driver).newInstance();
conn = java.sql.DriverManager.getConnection(url,userName,password);
}catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return conn;
}
回答by Amir Kost
Opening a DB connection is an expensive operation in terms of perfofmance. You should use a ConnectionPool for sharing connections among different requests.
就性能而言,打开数据库连接是一项代价高昂的操作。您应该使用 ConnectionPool 在不同请求之间共享连接。
回答by tbsalling
Database connections are long-running and should be re-used, unless you have a very low query rate.
数据库连接是长时间运行的,应该重复使用,除非您的查询率非常低。
回答by NickJ
Getting a database connection is quite an expensive operation, so it is advisable to re-use a connection if possible. Consider also using connection pooling, which will maintain a number of connections for you, so you can just grab one from the pool when needed. The method shown above might not need to change, it depends on the DBConnection() method you call.
获取数据库连接是一项非常昂贵的操作,因此建议尽可能重用连接。还可以考虑使用连接池,它将为您维护许多连接,因此您可以在需要时从池中获取一个。上面显示的方法可能不需要更改,这取决于您调用的 DBConnection() 方法。
回答by duffymo
Connections are not thread safe, so sharing them across requests is not a good idea.
连接不是线程安全的,因此跨请求共享它们不是一个好主意。
A better idea is to pool connections and keep their scope as narrow as possible: check the connection out of the pool, use it, close it in transaction scope.
一个更好的主意是将连接池化并尽可能缩小它们的范围:从池中检查连接,使用它,在事务范围内关闭它。
回答by cloudy_weather
I completely agree with @Amir Kost, in terms of performances, opening a DB connection in one of the slowest operation that you can do, and if you have restrictive real time constraints it could be a big issue. I do not know if you are using a framework or not, but a good practice is to publish a bean which wrap a pool of connection and every time that you need to interact directly with the db, you get the current open connection (which usually corresponds to a so called "session"). I suggest to you, (even if you are not using any framework) to reproduce this technicality.
我完全同意@Amir Kost 的观点,就性能而言,以您可以执行的最慢操作之一打开数据库连接,如果您有严格的实时约束,这可能是一个大问题。我不知道你是否在使用框架,但一个好的做法是发布一个封装连接池的 bean,每次你需要直接与数据库交互时,你都会得到当前打开的连接(通常对应于所谓的“会话”)。我建议您(即使您没有使用任何框架)重现这种技术性。
回答by javadev
If you want only one instance of Connection, you can make use of the Singleton pattern, you can consider :
如果你只想要一个 Connection 实例,你可以利用 Singleton 模式,你可以考虑:
public class Connector {
private static final String URL = "jdbc:mysql://localhost/";
private static final String LOGIN = "root";
private static final String PASSWORD = "azerty";
private static final String DBNAME = "videotheque";
private static Connector connector;
private static Connection connection;
private Connector() {
}
public synchronized static Connector getInstance() {
if (connector == null) {
connector = new Connector();
}
return connector;
}
public static Connection getConnection() {
if (connection == null) {
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
c = DriverManager.getConnection(URL + DBNAME, LOGIN, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c;
}
return connection;
}
}
}
And then, you can call : Connector.getInstance().getConnection()
然后,您可以调用: Connector.getInstance().getConnection()