如何在jsp页面中关闭连接

时间:2014-05-07 11:21:30

标签: jsp

我正在使用jsp,因为我正在创建数据库连接,我想关闭连接now.plz帮助我 这是我的代码

<%
Class.forName("com.mysql.jdbc.Driver");

System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms1?user=root&password=root");
System.out.println("Connection created");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from equip_master");
%>

  <table class="main" align="center" border="1">
  <tr>
    <td class="did">Equipment Id</td>
    <td class="dname">Equipment Name</td>
  </tr>
  </table>

  <div class="overflow1">
  <table class="main scroll1" align="center" border="1">
  <% while (rs.next()) {%>
  <tr onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this, false);" onclick="DoNav('<%=rs.getString("equp_id") %>');">
    <td class="did"><%=rs.getString("equp_id") %></td>
    <td class="dname1"><%=rs.getString("equp_name")%></td>

 </tr>
  <%}
  %>
 </table>
 </div>

1 个答案:

答案 0 :(得分:1)

将所有相关数据库代码放在try块中并将其添加到其中

   <%    
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");

System.out.println("driver loaded");
System.out.println("Driver is loaded");
 con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms1?user=root&password=root");
System.out.println("Connection created");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from equip_master");
%>

  <table class="main" align="center" border="1">
  <tr>
    <td class="did">Equipment Id</td>
    <td class="dname">Equipment Name</td>
  </tr>
  </table>

  <div class="overflow1">
  <table class="main scroll1" align="center" border="1">
  <% while (rs.next()) {%>
  <tr onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this, false);" onclick="DoNav('<%=rs.getString("equp_id") %>');">
    <td class="did"><%=rs.getString("equp_id") %></td>
    <td class="dname1"><%=rs.getString("equp_name")%></td>

 </tr>
  <%}
  %>
 </table>
 </div>

<%} catch (SQLException ex) {
                String message = "ERROR: " + ex.getMessage();
                ex.printStackTrace();
            } finally {
                if (con != null) {
                    // closes the database connection
                    try {
                        con.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }}%>
这里的

消息是一个字符串,可以作为响应传递给另一个页面。例如,它上传或出现一些错误,只要有一个..