我正在尝试使用我的 Java 代码连接到 Amazon Redshift 数据库。我在 AWS 网站上找到了一个应该可以工作的代码片段。然而,我在实现 JDBC 驱动程序时遇到了问题。 这是网站和网站中的代码:https://docs.aws.amazon.com/redshift/latest/mgmt/connecting-in-code.html
package connection;
import java.sql.*;
import java.util.Properties;
public class Docs {
//Redshift driver: "jdbc:redshift://x.y.us-west-
2.redshift.amazonaws.com:5439/dev";
//or "jdbc:postgresql://x.y.us-west-2.redshift.amazonaws.com:5439/dev";
static final String dbURL = "***jdbc cluster connection string ****";
static final String MasterUsername = "***master user name***";
static final String MasterUserPassword = "***master user password***";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Dynamically load driver at runtime.
//Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver
//Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver
Class.forName("com.amazon.redshift.jdbc.Driver");
//Open a connection and define properties.
System.out.println("Connecting to database...");
Properties props = new Properties();
//Uncomment the following line if using a keystore.
//props.setProperty("ssl", "true");
props.setProperty("user", MasterUsername);
props.setProperty("password", MasterUserPassword);
conn = DriverManager.getConnection(dbURL, props);
//Try a simple query.
System.out.println("Listing system tables...");
stmt = conn.createStatement();
String sql;
sql = "select * from information_schema.tables;";
ResultSet rs = stmt.executeQuery(sql);
//Get the data from the result set.
while(rs.next()){
//Retrieve two columns.
String catalog = rs.getString("table_catalog");
String name = rs.getString("table_name");
//Display values.
System.out.print("Catalog: " + catalog);
System.out.println(", Name: " + name);
}
rs.close();
stmt.close();
conn.close();
}catch(Exception ex){
//For convenience, handle all errors here.
ex.printStackTrace();
}finally{
//Finally block to close resources.
try{
if(stmt!=null)
stmt.close();
}catch(Exception ex){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Finished connectivity test.");
}
}
我获得了连接凭据,但收到以下错误。
java.lang.ClassNotFoundException:com.amazon.redshift.jdbc4.Driver
这是由这条线引起的:
Class.forName("com.amazon.redshift.jdbc.Driver");
我没有在任何地方实现此驱动程序,因此该错误是有道理的。问题是 IntelliJ IDEA 有一个插件(Database Navigator),但它不能按预期工作,我无法在他们的论坛上获得任何帮助。
还有其他包含 JDBC 驱动程序以便代码可以使用它(在 IntelliJ 中)吗?
编辑:
将 JAR 添加为外部库后,我的项目如下所示:
但是,当我运行代码时,我得到了同样的错误。
您可以像这样导入 Amazon Redshift JDBC 驱动程序:
从以下 URL 下载 Amazon Redshift JDBC 驱动程序。
https://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html#download-jdbc-driver
将下载的 Jar 添加到您的类路径中。
它会起作用的。
您可以按照@Corentin 建议的步骤执行步骤#2。
请添加以下 Maven/Gradle 依赖项或从以下 URL 下载 Amazon Redshift JDBC 驱动程序
https://mvnrepository.com/artifact/com.amazon.redshift/redshift-jdbc42/2.1.0.24
通过传递正确的 dbURL 和凭据来运行程序。会起作用的