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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With