Servlet连接MySQL的问题
在控制台应用时,可以正常连接
但是当把改称在Servlet中连接数据库,就出现获得Connection为空的情况。
还请大家有遇到过该问题的帮帮忙,指点迷津。
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"); }}
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"); } }