有人可以告诉我如何将java文件连接到postgresql数据库(如果可能,请使用代码n说明)
答案 0 :(得分:4)
Google是一个好的开始
答案 1 :(得分:3)
以下是test.java
import java.sql.*;
class test
{
public static void main(String[] args) {
String hostname="", dbname="", username="", password="";
try {
int argno = 0;
hostname = args[argno++];
dbname = args[argno++];
username = args[argno++];
password = args[argno++];
} catch (Exception ex) {
System.err.println("Usage: java -cp driver.jar:. test [hostname] [dbname] [username] [password]");
System.exit(1);
}
try {
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager.getConnection(
"jdbc:postgresql://"+hostname+"/"+dbname,
username,
password
);
ResultSet rs = connection.createStatement().executeQuery(
"select version() as version"
);
while ( rs.next() ) {
System.out.println(rs.getString("version"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
从current driver下载JDBC download page,编译并在Unices上运行如下:
java -cp [driver_file_name].jar:. test [hostname] [dbname] [username] [password]
在Windows上:
java -cp [driver_file_name].jar;. test [hostname] [dbname] [username] [password]
答案 2 :(得分:1)