日期:2014-05-20  浏览次数:20896 次

Servlet连接MySQL的问题
在控制台应用时,可以正常连接
但是当把改称在Servlet中连接数据库,就出现获得Connection为空的情况。
还请大家有遇到过该问题的帮帮忙,指点迷津。
Java code

package reader;
import java.sql.*;


public class DBConnector {
    static{
        try{
             Class.forName("org.gjt.mm.mysql.Driver");
        }
        catch (ClassNotFoundException e) {
             System.err.println("ClassNotFoundException in Class- DBConnector");              
        }
    }
    public static Connection getConnection(String host,String dbName,String username,String password){
        Connection connection = null;
        try{
            String url = "jdbc:mysql://"+host+"/"+dbName+"?useUnicode=true&characterEncoding=UTF-8";
            connection = DriverManager.getConnection(url,username,password);
        }
        catch(SQLException e){
            System.err.print(e);
        }
        return connection;
    }
    
    public static void main(String[] args){
        Connection conn = DBConnector.getConnection("localhost", "dbname", "root", "");
        if(conn != null){
            System.out.println("conn is not null");
        }
        System.out.println("OK");
    }
}


如上为数据库连接类,在控制台应用程序中测试可用。
但是放到Servlet中如下,则不行:
Java code

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        Connection conn = getConnection("127.0.0.1:3306", "dbname", "root", "");
        String sql = "SELECT * FROM";
        Statement state;
        ResultSet rs = null;
        PrintWriter out = response.getWriter();
        if(conn != null){
            try {
                
                state = conn.createStatement();
                rs = state.executeQuery(sql);
                while(rs.next()){
                    out.println(rs.getString(1)+rs.getString(2)+rs.getString(3));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        else{
            out.println("Conn is null");
        }
    }




------解决方案--------------------
应该写成Connection conn = DBConnector.getConnection("127.0.0.1:3306", "dbname", "root", "");