import java.sql.*; /* You can compile and run this example with a command like: javac BasicSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar BasicSample You can download the postgres JDBC driver jar from https://jdbc.postgresql.org. */ public class BasicSample { public static void main(String[] args) throws ClassNotFoundException, SQLException { // Load the postgres JDBC driver. Class.forName("org.postgresql.Driver"); Connection db; // Connect to the "bank" database. String url = "jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable"; if (args.length > 0) { url = args[0]; System.out.printf("url= %s\n", url); db = DriverManager.getConnection(url); } else { System.out.printf("default= %s\n", url); db = DriverManager.getConnection(url, "maxroach", ""); } try { // Create the "accounts" table. db.createStatement().execute("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT); truncate accounts;"); // for (int i = 0; i < 1000; i++) { // Insert two rows into the "accounts" table. // db.createStatement().execute(String.format("INSERT INTO accounts (id, balance) VALUES (%d, 1000);",i)); // //db.createStatement().execute(String.format("INSERT INTO accounts (id, balance) VALUES (%d, 1000) on conflict (id) do update set balance=excluded.balance",i)); // } // dynamic SQL does not alllow batching // Statement stmt = db.createStatement(); // does not convert PreparedStatement stmt = db.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, 1000) returning id,balance;"); // works PreparedStatement stmt = db.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, 1000)"); // works PreparedStatement stmt = db.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, 1000) in conflict (id) do update set balance=excluded.balance"); PreparedStatement stmt = db.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, 1000) on conflict (id) do update set balance=excluded.balance"); for (int i = 1000; i < 2000; i++) { // Insert two rows into the "accounts" table. stmt.setInt(1, i); stmt.addBatch(); } int[] count = stmt.executeBatch(); for (int i : count){ System.out.println(i); } // Print out the balances. // System.out.println("Initial balances:"); // ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts"); // while (res.next()) { // System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance")); // } } finally { // Close the database connection. db.close(); } } }