如何从JSP页面连接到POSTGRESQL数据库

时间:2018-05-08 11:37:02

标签: java postgresql

我正在尝试连接到PostgreSQL数据库,但是下面的代码在页面上什么也没有产生任何帮助,我们将不胜感激。

此页面托管在apache tomcat中,并且geoserver已连接到同一台计算机上的同一数据库并且工作正常。

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.* " %>
<%@ page import="java.io.*" %>
<%
try {
    String driver = "org.postgresql.Driver";
    String url = "jdbc:postgresql://localhost/mahaproperties";
    String username = "postgres";
    String password = "Apple123!@#";
    String myDataField = null;
    String myQuery = "select * from public.maharashtra_parcel LIMIT 1000";
    Connection myConnection = null;
    PreparedStatement myPreparedStatement = null;
    ResultSet myResultSet = null;
    Class.forName(driver).newInstance();
    myConnection = DriverManager.getConnection(url,username,password);
    System.out.println("Opened database successfully");
    myPreparedStatement = myConnection.prepareStatement(myQuery);
    ResultSet rs = myPreparedStatement.executeQuery();

    ResultSetMetaData rsmd = rs.getMetaData();
    int  totalColumn = rsmd.getColumnCount();


    out.println("<table border='1' style='border-collapse:collapse'>");
    out.println("<tr>");

    for(int i=1;i<=totalColumn;i++)
    {
        String columnName = rsmd.getColumnName(i);
        out.println("<th>"+columnName+"</th>");
    }
    out.println("</tr>");

    while(rs.next())
    {    
        out.println("<tr>");
        for(int col=1;col<=totalColumn;col++)
        {            
            Object obj= rs.getObject(col);                    
            out.println("<td>"+ String.valueOf(obj) +"</td>");
        } 
        out.println("</tr>");
    }
    out.println("</table>");

}
catch(ClassNotFoundException e){
    e.printStackTrace();
}
catch (SQLException ex) {
    out.print("SQLException: "+ex.getMessage());
    out.print("SQLState: " + ex.getSQLState());
    out.print("VendorError: " + ex.getErrorCode());
}
%>

0 个答案:

没有答案