Servlet连接数据库

局部变量:Connetion conn=null;

             Statement stmt=null;

             ResultSet rs=null;

try{

Class.forName(“com.mysql.jdbc.Driver”);

conn=DriverManager.getConnection(“jdbc:mysql://localhost/databasename?user=sa$password=sa;”);

stmt=conn.createStatement();

rs=stmt.executeQuery(“select * from tablename”);

while(rs.Next()){

rs.getString(“columnName”);

}

}catch(ClassNotFoundException ex){

e.printStackTrace();

}

catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) {
                    rs.close();
                    rs = null;
                }
                if(stmt != null) {
                    stmt.close();
                    stmt= null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

注意:1.检查连接字符串。

2.确认数据库服务器已经启动

3.把jdbc的驱动程序拷到tomcat中。

App的WEB-INF下的lib目录中需要相应的jar包无用。

原文地址:https://www.cnblogs.com/guaniu/p/2324030.html