3

I'm trying to insert an Array of Strings into Postgres. I get an invalid type error from Postgres.

public static void main(String[] args) throws SQLException {
    String[] skus = { "0514", "0414", "0314", "0214", "0114", "1213", "1113", "1013", "0913", "0813", "0713", "0613" };
    String sqlString = "Insert into dbo.Inventory_Metrics skus values(?)";
    Connection conn = DriverManager.getConnection(getPostgresConnUrl());
    PreparedStatement ps = conn.prepareStatement(sqlString);

    //THIS NEXT LINE THROWS AN ERROR

    ps.setObject(1, skus, java.sql.Types.NVARCHAR, skus.length);
    int status = ps.executeUpdate();
    ps.close();

    System.out.print(status);
}
public static String getPostgresConnUrl() {
    String database = "mycode";
    String userName = "xxxxxxxx";
    String password = "xxxxxxxx";
    return "jdbc:postgresql://192.168.0.50:5432/" + database + "?user=" + userName + "&password=" + password;

}
4
  • But you have a single question mark, and an array of values. You might try a string of comma-separated values instead. Commented Sep 23, 2014 at 15:33
  • 1
    The JDBC API doesn't work this way. Please describe what you want to achieve. On top of that: PostgreSQL doesn't support the NVARCHAR type afaik Commented Sep 23, 2014 at 16:06
  • ps.setObject(1, skus, java.sql.Types.VARCHAR, skus.length); //Fixes error, post it as the answer. Commented Sep 23, 2014 at 19:10
  • Near-identical repost at stackoverflow.com/q/26005620/398670 . (+1, thanks for including your code and the error message. In future, your PostgreSQL and PgJDBC version should also be included in all questions). Commented Sep 24, 2014 at 2:42

1 Answer 1

6

You must use the JDBC array API, per the documentation.

You can't just setObject an array in JDBC. It'd be nice if that's how it works, but it isn't. You're expected to handle arrays specially.

Array jdbcSkus = con.createArrayOf("VARCHAR", skus);
pstmt.setArray(2, jdbcSkus);
Sign up to request clarification or add additional context in comments.

2 Comments

@NathanHughes Re your deleted answer - Most DBMSs support native arrays, and it's almost never right to store comma-separated data if you can avoid it.
agreed, it was just unclear what the OP wanted. i assumed nvarchar was right and went with that, then deleted when I saw Mark's comment. couldn't agree more about avoiding comma-separated data (almost never might not be strong enough wording). not sure an array is much better though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.