2011年6月22日星期三

PostgreSQL Java 连接 Tomcat下 JNDI , FATAL: password authentication failed for user "" 报错 等问题

1) PostgresQL java 连接
import java.sql.*;

public class PostgresConnector {
 public static void main(String[] args) {
  try {
   Class.forName("org.postgresql.Driver");
   Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/TableName","username","password");
   System.out.println(conn.isClosed());
   Statement stmt=conn.createStatement();
   ResultSet rs=stmt.executeQuery("SELECT * from batiment");
   while(rs.next())
   {
    System.out.println(rs.getString(1));
   }
   conn.close();
  }
  catch(Exception ex){
      ex.printStackTrace();
   System.out.println("error!");
  }
 }
}  



2)Tomcat下 JNDI

   
第一步、配置tomcat目录下/conf下的context.xml (或者是netbeans      web pages 下 META-INF 的context.xml)
<Context antiJARLocking="true" path="/setms">
    <Resource name="jdbc/setms" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="postgres" password="12345" driverClassName="org.postgresql.Driver" url="jdbc:postgresql://localhost:5432/setmanager_dev" />
</Context>

第二步、配置项目中/WEB-INF/下的web.xml
  <resource-ref>
    <res-ref-name>jdbc/setms</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

第三步、测试数据源
 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@page import="java.sql.*, javax.sql.*, javax.naming.*"%>
<html>
<head>
<title>Using a DataSource</title>
</head>
<body>
<h1>Using a DataSource</h1>
<%
    DataSource ds = null;
    Connection conn = null;
    ResultSet result = null;
    Statement stmt = null;
    ResultSetMetaData rsmd = null;
    try{
      Context context = new InitialContext();
      Context envCtx = (Context) context.lookup("java:comp/env");
      ds =  (DataSource)envCtx.lookup("jdbc/setms");
      if (ds != null) {
        conn = ds.getConnection();
        stmt = conn.createStatement();
        result = stmt.executeQuery("SELECT * FROM Personne");
       }
     }
     catch (SQLException e) {
        System.out.println("Error occurred " + e);
      }
      int columns=0;
      try {
        rsmd = result.getMetaData();
        columns = rsmd.getColumnCount();
      }
      catch (SQLException e) {
         System.out.println("Error occurred " + e);
      }
 %>
 <table width="90%" border="1">
   <tr>
   <% // write out the header cells containing the column labels
      try {
         for (int i=1; i<=columns; i++) {
              out.write("<th>" + rsmd.getColumnLabel(i) + "</th>");
         }
   %>
   </tr>
   <% // now write out one row for each entry in the database table
         while (result.next()) {
            out.write("<tr>");
            for (int i=1; i<=columns; i++) {
              out.write("<td>" + result.getString(i) + "</td>");
            }
            out.write("</tr>");
         }

         // close the connection, resultset, and the statement
         result.close();
         stmt.close();
         conn.close();
      } // end of the try block
      catch (SQLException e) {
         System.out.println("Error " + e);
      }
      // ensure everything is closed
    finally {
     try {
       if (stmt != null)
        stmt.close();
       }  catch (SQLException e) {}
       try {
        if (conn != null)
         conn.close();
        } catch (SQLException e) {}
    }

    %>
</table>
</body>
</html>


记得拷贝postgresql-9.0-801.jdbc4.jar 到WEB-INF  lib 下 或 tomcat目录下/lib下




name:指定Resource的JNDI的名字、
auth:指定管理Resource的Manager,它有两个值:Container 和Application,Container并表示有容器来创建Resource,Application表示有Web应用来创建和管理Resource、
type:指定Resource所属的Java类名、
maxActive:指定数据库连接池中处于活动状态的数据库连接的最大数目,取值为0,表示不受限制、
maxIdle:指定数据库连接池中处于空闲状态的数据库连接的最大数目,取值为0,表示不受限制、
maxWait:指定数据库连接池中的数据库连接处于空闲状态的最长时间(以毫秒为单位),超过这一时间将会抛出异常,取值为-1,表示可以无限制等待、
username:指定连接数据库的用户名、
password:指定连接数据库的口令、
driverClassName:指定连接数据库的JDBC驱动程序
url:指定连接数据库的URL、


  FATAL: password authentication failed for user "" 问题
是由于user 权限不够, 检查postgreSQL中的表是不是 相应user (默认是postgres), 再一次检查context.xml中的user!

没有评论:

发表评论