用Servlet连接Mysql每次只能显示一次,然后要用Eclipse重新发布才能再次显示

来源:百度知道 编辑:UC知道 时间:2024/05/25 21:27:40
我的程序如下:
请帮我看下:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class JDBCServlet extends HttpServlet {
protected Connection conn=null;
public void init(ServletConfig config)throws ServletException{

super.init(config);
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/student";
String username="root";
String pwd="123456";
try{
Class.forName(driver).newInstance();
conn=DriverManager.getConnection(url,username,pwd);
System.out.println("Connection successful..");

}catch(SQLException se){
System.out.println(se);

}catch(Exception e){

e.printStackTrace();
}
}
public void executeSQL(PrintWriter out)throws SQLException{
Statement stmt=conn.createStatement();
String sql="select * fro

原因是你把conn初始化写在init里了,调完get方法以后conn已经关闭了,这样下次调这个servlet的时候servlet容器里已经有这个servlet了,不会调init方法,而是把上次的servlet拿出来给你用,但这个对象里的conn已经被你关闭了,所以这时候没有连接
你得把获得连接的代码写在doGet里,这样你每次调用get方法的时候都有个新的连接