我在一本书中学习了一个连接mysql数据库的例子。代码文件JDBCServletExample.java如下:
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JDBCServletExample extends HttpServlet {
private Connection con;
public void init() throws ServletException  
{
super.init();
try{
              String driverName="com.mysql.jdbc.Driver";
              String userName="root";

              String userPasswd="1234"; //密码

              String dbName="test"; //数据库名

              String tableName="person"; //表名
                      
                     
                     
                      String url="jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd;
                      Class.forName(driverName).newInstance(); //连接字符串
                     
//获取连接,放入成员变量con
                      Connection    con =DriverManager.getConnection(url);
}

catch(Exception e)
{
e.printStackTrace();
}
           System.out.println("off init function");     
}
public void  service (HttpServletRequest request, HttpServletResponse response)
            throws ServletException,IOException
{
//读取前端Form提交来的参数
       
        String name=request.getParameter("name");
String sex=request.getParameter( "sex");
String birthday=request.getParameter("birthday");
String email=request.getParameter("email");
        
String reg="insert into person values(?,?,?,?)";
try{
                       
                        PreparedStatement stmt=con.prepareStatement(reg);
stmt.setString(1,name);
stmt.setString(2,sex);
stmt.setString(3,birthday);
stmt.setString(4,email);
stmt.executeUpdate();//执行update
                        System.out.println("insert ok!");
}
catch(Exception e)
{
e.printStackTrace();
}}} 文件中定义了一个JDBCServletExample类,类内定义了两个函数init()和service(),定义了一个私有变量con.上面的代码运行的时候,在service函数中con就不知指向哪里了。如果init()中绿颜色的代码拿到service()中来就可以连接上数据库进行数据的插入了。我想知道,从代码上看,感觉在类内定义一个私有变量,现在init函数中连接上数据库,然后再在service函数中直接用就可以了。但是运行来怎么就不可以了呢?我的服务器是resin-2.1.16.