tomcat连接mysql问题
import java.io.IOException;import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowRs extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter pw = response.getWriter();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
pw.println("<table boder=1>");
pw.println("<tr><td>Content:</td></tr>");
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata?user=root&password=root");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from emp");
while(rs.next()) {
pw.println("<tr>");
pw.println("<td>" + rs.getString("sal") + "</td>");
pw.println("</tr>");
}
pw.println("</table>");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
while(rs != null) {
rs.close();
rs = null;
}
while(stmt != null) {
stmt.close();
rs = null;
}
while(conn != null) {
conn.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
不报错 但网页也显示不出 CUP暴涨到100% --------------------编程问答-------------------- finally 部分改成一下代码试试:
finally {--------------------编程问答-------------------- stmt = conn.createStatement();
if (rs != null) {
try{ rs.close(); }catch(Exception e){}
}
if (stmt != null) {
try{ stmt.close(); }catch(Exception e){}
}
if (conn != null) {
try{ conn.close(); }catch(Exception e){}
}
}
rs = stmt.executeQuery("select * from emp");
这里需要判断一下 conn是否为空,只能不为空的情况下才做,否则包空指针了
if (conn != null){
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from emp");
.
.
.
.
} --------------------编程问答-------------------- 谢谢!成功了…… --------------------编程问答-------------------- 不报错 但网页也显示不出 CUP暴涨到100%
这种情况一般就是连接没有正确关闭,资源没有正确释放
虽然小的一些可以依靠GC来处理,但以上这些是无法确定的。
类似的还有I/O处理
补充:Java , Web 开发