javasqlpostgresqlprepared-statement

Shortcut for Question marks in preparedStatement for parameterized query


I have a table with 200 columns. I am trying to prepare an "insert into this table" from excel file to a database table. I should put 190 question marks more.

ps = con.prepareStatement("INSERT INTO `user`(`username`, `realname`, `password`, `email`, `gym`, `belt`, `dateofbirth`, `profilepic`, `biography`, `motto`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

Is there a limit on how many question marks I can put? (I am working on PostgreS database) Is there a shortcut for this syntax? like (200*?)

Note: I am using Java.


Solution

  • You can use String.join()

    int columns = 200;
    String questionMarks = String.join(",", Collections.nCopies(columns, "?"));
    String insertSql = String.format("INSERT INTO `user`(`username`, `realname`, `password`, `email`, `gym`, `belt`, `dateofbirth`, `profilepic`, `biography`, `motto`) VALUES (%s)", questionMarks);
    ps = con.prepareStatement(insertSql);
    

    You could also omit column names if you're inserting values for all columns in the same order as they appear in the table.

    String insertSql = String.format("INSERT INTO `user` VALUES (%s)", questionMarks);