@@ -26,10 +26,12 @@ private void showHome(HttpServletRequest req, HttpServletResponse resp)
2626
2727 private void showDatabase (HttpServletRequest req , HttpServletResponse resp )
2828 throws ServletException , IOException {
29+ Connection connection = null ;
30+ Statement stmt = null ;
2931 try {
30- Connection connection = getConnection ();
32+ connection = getConnection ();
3133
32- Statement stmt = connection .createStatement ();
34+ stmt = connection .createStatement ();
3335 stmt .executeUpdate ("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)" );
3436 stmt .executeUpdate ("INSERT INTO ticks VALUES (now())" );
3537 ResultSet rs = stmt .executeQuery ("SELECT tick FROM ticks" );
@@ -42,15 +44,45 @@ private void showDatabase(HttpServletRequest req, HttpServletResponse resp)
4244 resp .getWriter ().print (out );
4345 } catch (Exception e ) {
4446 resp .getWriter ().print ("There was an error: " + e .getMessage ());
47+ } finally {
48+ ensureConnectionClosed (connection , stmt , null );
4549 }
4650 }
4751
52+ public void ensureConnectionClosed (Connection conn , Statement ps , ResultSet rs ) {
53+ if (rs != null ) {
54+ try {
55+ rs .close ();
56+ }
57+ catch (SQLException e ) {
58+ }
59+ }
60+
61+ if (ps != null ) {
62+ try {
63+ ps .close ();
64+ }
65+ catch (SQLException e ) {
66+ }
67+ }
68+
69+ if (conn != null ) {
70+ try {
71+ conn .close ();
72+ }
73+ catch (SQLException e ) {
74+ }
75+ }
76+ }
77+
4878 private Connection getConnection () throws URISyntaxException , SQLException {
4979 URI dbUri = new URI (System .getenv ("DATABASE_URL" ));
5080
5181 String username = dbUri .getUserInfo ().split (":" )[0 ];
5282 String password = dbUri .getUserInfo ().split (":" )[1 ];
53- String dbUrl = "jdbc:postgresql://" + dbUri .getHost () + dbUri .getPath ();
83+ int port = dbUri .getPort ();
84+
85+ String dbUrl = "jdbc:postgresql://" + dbUri .getHost () + ":" + port + dbUri .getPath ();
5486
5587 return DriverManager .getConnection (dbUrl , username , password );
5688 }
0 commit comments