例如,我编写了以下PHP代码并在redshift上运行,如下所示。
<?php
$connect = pg_connect("host=xx.xxxx.us-east-1.redshift.amazonaws.com port=xxxx dbname=testdb user=xxxx password=xxxxxx");
$query = "select name, email from mytable LIMIT 7";
$result = pg_query($connect,$query);
while(($row = pg_fetch_array($result)) != null) {
$name = $row[0];
$email = $row[1];
echo $name." <<>> ".$email." <<>> ";
}
?>
我保存了上面的php文件并以下面的方式执行。
myuser@ip-20-143-43-144:/home/myuser$ php runquery.php <Enter>
然后它给我输出。
我想用java测试同样的东西。所以我从aws拿了例子并保存在同一个地方。
public class ConnectToCluster {
static final String dbURL = "jdbc:postgresql://xxxx.xxxxx.us-east-1.redshift.amazonaws.com:xxxx/testdb";
static final String MasterUsername = "XXXX";
static final String MasterUserPassword = "XXXXXX";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Dynamically load postgresql driver at runtime.
Class.forName("org.postgresql.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
文件也保存在同一位置。那么,有人可以告诉我如何在命令中运行这个java文件,就像我为php做的那样。
答案 0 :(得分:1)
(1)从以下链接下载postgresql JDBC驱动程序,并将其放在ConnectToCluster.java的同一目录中。
(2)在java文件的头部添加缺失的行(import java library)。
import java.sql.*;
import java.util.*;
public class ConnectToCluster {
...
(3)运行以下命令。
javac ConnectToCluster.java && java -cp .:postgresql-8.4-703.jdbc4.jar ConnectToCluster