Eclipse帮助中的Postgres JDBC连接

Cha*_*ite 10 java postgresql jdbc

我正在尝试在eclipse中使用postgres jdbc连接.使用Data Source Explorer会很好,但是现在我只想尝试获得基本连接.到目前为止我所做的是下载postgres JDBC连接器.然后我尝试了两种不同的东西.首先,首选项 - >数据管理,我试图添加postgres连接器.其次,我将jar添加到我的项目中并尝试使用Class.forName("org.postgresql.Driver")加载驱动程序; 但都没有奏效.有没有人有任何想法?

谢谢,查理

efl*_*les 20

这就是我建立连接的方式:(我不知道这是否是"最佳实践",但它有效.)

导入驱动程序:

  1. 右键单击您的项目
  2. 选择房产
  3. 选择 Java build path
  4. 选择Add external JARS..并选择JDBC驱动程序的位置.

这是我的代码:

try{
    Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException cnfe){
      System.out.println("Could not find the JDBC driver!");
      System.exit(1);
    }
Connection conn = null;
try {
    conn = DriverManager.getConnection
                   (String url, String user, String password);
     } catch (SQLException sqle) {
       System.out.println("Could not connect");
       System.exit(1);
     }
Run Code Online (Sandbox Code Playgroud)

网址可以是以下格式之一:

jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
Run Code Online (Sandbox Code Playgroud)


小智 -1

以下是将 PostgreSQL 连接到您的应用程序的一种方法:

  1. 获取一个实例org.postgresql.ds.PGSimpleDataSource
  2. 使用与您的数据库匹配的值进行设置(请参阅下面的方法)
  3. 继续使用数据源,就像使用任何其他数据源一样,我假设此时您会对该DataSource.getConnection()方法感兴趣。

配置此特定数据源的专有方法是setServerName()setDatabaseName()和。setUser()setPassword()

除了测试之外,我不建议这样做,而且您的问题可能在于您尝试使用以下方法获取对象实例的Class.forName()方式: 获取对象实例的方法有几乎十几种,但存在细微的差别,我建议用谷歌搜索它,因为这是一个很多人已经在互联网上写过的主题。