I am developing a dynamic web project on eclipse.
Below is an example of connecting MySQL using DataSource. Is it the correct way? I mean is it normal to get connection in a Servlet?
Moreover, I find this way to get/close connection is tedious because I need to write exact same part of codes every time when I want to get/close connection. I think there should be a better way. Could someone give me some suggestions?
Thank you!
@WebServlet(name="HelloUser", urlPatterns={"/hellouser"})
public class HelloUserServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DataSource ds = MyDataSourceFactory.getMySQLDataSource();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(...);
...
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Starting from Java 7 you can use try-with-resource
( JDBC api is updated to implement Autocloseable) .
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it
Eg
try (Connection con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(...)) {...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.