使用JDBC连接AWS Redshift

3

我希望使用JDBC连接并将数据插入到我的Amazon Redshift表中。 我编写了以下代码,但在Class.forName行处一直出现错误。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class RedShiftDataEmitter {
    static final String redshiftUrl = "jdbc:redshift://xxxxxxxxx:5439/xxxxxx";
    static final String masterUsername = "xxxxxxx";
    static final String password = "xxxxxxx";

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;

        try {
            Class.forName("com.amazon.redshift.jdbc41.Driver");
            Properties properties = new Properties();
            properties.setProperty("user", masterUsername);
            properties.setProperty("password", password);
            connection = DriverManager.getConnection(redshiftUrl, properties);
            // Further code to follow
        } catch(ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }
}

提醒一下,我可以使用SQL Workbench连接到同一集群。我的pom.xml如下:

<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-redshift -->
  <dependency>
      <groupId>com.amazon.redshift</groupId>
      <artifactId>redshift-jdbc41</artifactId>
      <version>1.2.1.1001</version>
  </dependency>

你的Driver类是否在类路径上?异常堆栈跟踪是什么? - SMA
java.lang.ClassNotFoundException: com.amazon.redshift.jdbc41.Driver 在java.net.URLClassLoader.findClass(URLClassLoader.java:381) 在java.lang.ClassLoader.loadClass(ClassLoader.java:424) 在sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) 在java.lang.ClassLoader.loadClass(ClassLoader.java:357) 在java.lang.Class.forName0(Native Method) 在java.lang.Class.forName(Class.java:264) - Nick
那么,你如何运行这个程序?你是将驱动器jar放在运行时类路径中吗?(编译代码时不需要它,因为你只使用标准的JDBC类)。 - JB Nizet
我在Maven中央库里找不到你发布的那个依赖项。你确定IntelliJ下载了这个依赖项吗?你是从哪里找到它的? - JB Nizet
我在 AWS 文档中找到了依赖项 - http://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection-with-maven.html - Nick
2
你是否按照你提供的链接中所述,将该仓库添加到pom文件中了? - JB Nizet
2个回答

12
  1. 首先在pom.xml中添加仓库,

<repositories>
  <repository>
      <id>redshift</id>
      <url>http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release</url>
  </repository>
</repositories>

  1. 现在添加Amazon Redshift Driver的Maven依赖jar包

<dependency>
  <groupId>com.amazon.redshift</groupId>
  <artifactId>redshift-jdbc42</artifactId>
  <version>1.2.1.1001</version>
</dependency>  

使用这个驱动程序 com.amazon.redshift.jdbc42.Driver

清理构建项目,现在应该可以工作了。


3

我找到了答案,问题在于Maven无法识别redshift依赖关系。您需要手动下载并添加jar(外部jar)。


3
如果Maven不能识别外部依赖项,则可以将以下行添加到pom文件中以解决问题。<repositories> <repository> <id>redshift</id> <url>http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release</url> </repository> </repositories> - iec2011007

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接