App下載
首頁javaconnectionJava JDBC - 如何連接PostgreSQL

Java JDBC - 如何連接PostgreSQL

我們想知道如何連接PostgreSQL。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class Main {
  public static void main(String[] args) throws Exception {
    String hostname = "", dbname = "", username = "", password = "";
    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"));
    }
  }
}