javaarrayspostgresqljdbc

JDBC - Inserting an array variable into a PostgreSQL table


I am trying to insert an array variable into the table. The code is shown below

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

class PostgreSQLJDBC {

    public static void main(String args[]) {
        Connection c = null;
        Statement stmt = null;
        Statement stmt1 = null;
        int id[] = new int[3];
        int no = 1;
        id[0] = 2;
        id[1] = 14;
        id[2] = 4;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager
                    .getConnection("jdbc:postgresql://localhost:5432/ass2",
                            "postgres", "post");
            c.setAutoCommit(true);
            System.out.println("Opened database successfully");
            stmt = c.createStatement();
            String sql1 = "INSERT INTO COMPANY (NO,ID) "
                    + "VALUES (7, id);";
            stmt1 = c.createStatement();
            stmt1.executeUpdate(sql1);
            stmt1.close();
            c.close();
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        System.out.println("Operation done successfully");
    }
}

This code compiles but gives an PSQLexception.

Could someone please help in fixing this


Solution

  • Try to use Prepared Statement so you can use setArray like this :

    But first of all you can't set int[] you have to convert it to Array, so you can use :

    Integer[] id = {2, 14, 4};
    Array array = connection.createArrayOf("INTEGER", id);
    

    Then create your Prepared Statement and set the array :

    String sql = "INSERT INTO COMPANY (NO, ID) VALUES (?, ?)";
    try (PreparedStatement pstmt = conn.prepareStatement(sql);) {
    
        pstmt.setInt(1, 7);   // Set NO
        pstmt.setArray(2, array);  // Set ID
    
        pstmt.executeUpdate();  // Execute the query
    }
    

    Note : please avoid UPPER LETTERS in the name of tables and columns in PostgreSQL! This can makes some problems, instead your query should look like :

    INSERT INTO company (no, id) VALUES (?, ?)