[英]Is it necessary to close jdbc connection in localhost
I use static methods in a java project that i build, to make queries to a localhost mysql db.我在我构建的 java 项目中使用静态方法来查询本地主机 mysql db。
Something like that:类似的东西:
public static void sqlQuery() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(localhost,root,password);
stmt = conn.prepareStatement(Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
}
My Question is if i can keep the conn variable without close it and reuse it again for another query.我的问题是我是否可以保留 conn 变量而不关闭它并再次将其重用于另一个查询。
No other app use this db and i can do that i want with only 1 connection..没有其他应用程序使用这个数据库,我可以做到我想要的只有 1 个连接..
PS Sorry for my bad english.. PS对不起我的英语不好..
You can reuse a connection in the same context.您可以在同一上下文中重复使用连接。 Once you have changed your context, you should close the former connection and reopen another connection.
一旦你改变了你的上下文,你应该关闭之前的连接并重新打开另一个连接。
连接不是线程安全的,因此仅使用一个连接会带来危险。您应该使用连接池,为每个逻辑活动提供一个新的逻辑连接。
You should always close resources like JDBC connection.您应该始终关闭 JDBC 连接等资源。 If you don't close them, it creates a resource leak and it can slow down your program.
如果您不关闭它们,则会造成资源泄漏,并且会减慢您的程序速度。
It is always advisable to close the connection, since its not a thread safe.始终建议关闭连接,因为它不是线程安全的。 It is also not advisable to keep the connection object as the singleton.
将连接对象保持为单例也是不可取的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.