java servlet与postgresql连接

时间:2013-09-04 12:08:28

标签: java postgresql servlets

我在使用postgresql连接java servlet时遇到了一些问题。 如果可以,请帮助我

String dbName = "jdbc:postgresql://localhost/schedule_of_holidays";
        String dbDriver = "org.postgresql.Driver";

        Class.forName(dbDriver);
        Connection con = DriverManager.getConnection(dbName, userName,
                password);
        System.out.println("Got Connection");
        Statement statement = con.createStatement();
        String sql = "select id from registration";
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()) {
            System.out.println(rs.getInt("id"));
        }

1 个答案:

答案 0 :(得分:4)

尝试使用此代码并记住一件事,然后运行您在以下位置的lib文件夹中添加postgresql-9.1-901.jdbc4.jar的代码:tomcat_home/webapps/<project_name>/WEB-INF/lib

如果没有此jar文件,您将获得ClassNotFoundException

         String dbName = "jdbc:postgresql://localhost/struts_new";
         String dbDriver = "org.postgresql.Driver";
         String userName = "postgres";
         String password = "postgres"; 

         try{
         Class.forName(dbDriver);
         Connection con = DriverManager.getConnection(dbName, userName, password);
         System.out.println("Got Connection");
         Statement statement = con.createStatement();
         String sql = "select * from login";
         ResultSet rs = statement.executeQuery(sql);
         while (rs.next()) {
             System.out.println(rs.getString("uname"));
         }
         }catch(SQLException e){
            e.printStackTrace();
         }

希望此代码可以帮助您。