0

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

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"));
        }
4

1 回答 1

5

尝试此代码并记住一件事,然后再运行您postgresql-9.1-901.jdbc4.jar在 lib 文件夹中添加到以下位置的代码: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();
         }

希望这段代码对您有所帮助。

于 2013-09-04T12:27:51.880 回答