Files
javaplay/DB/PostgreSqlExample copy.java
2023-03-02 18:06:10 -06:00

44 lines
1.9 KiB
Java

/*
Compile:
javac PostgreSqlExample.java
Run:
java -cp postgresql-42.5.4.jar;. PostgreSqlExample
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PostgreSqlExample {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://192.168.10.138:5432/example", "postgres", "postgres")) {
System.out.println("Java JDBC PostgreSQL Example");
// When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within
// the class path. Note that your application must manually load any JDBC drivers prior to version 4.0.
// Class.forName("org.postgresql.Driver");
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
statement.setFetchSize(10);
System.out.println("Reading records.");
//ResultSet resultSet = statement.executeQuery("SELECT * FROM test1 a, test1 b, test1 c, test1 d, test1 e, test1 f, test1 g, test1 h, test1 i, test1 j limit (10)");
ResultSet resultSet = statement.executeQuery("SELECT * FROM test1 a, test1 b, test1 c, test1 d, test1 e, test1 f, test1 g, test1 h, test1 i, test1 j");
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.println("-"+ resultSet.getString(2));
}
} /*catch (ClassNotFoundException e) {
System.out.println("PostgreSQL JDBC driver not found.");
e.printStackTrace();
}*/ catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}