Search code examples
javajdbcprepared-statementsqlexception

Error in passing SQL command through a prepared statement via jdbc


I am trying to create table where the program gets the number of rows and columns during runtime.

Here's the code:

String sql = 
  "CREATE TABLE if not exists itemset (?";
up1 = con.prepareStatement(sql);
for(int j=1; j < ccolumns; j++) {
  sql += ",?";
}
sql += ")";
System.out.println(sql);
for(int j=1; j < ccolumns+1; j++) {
  System.out.println(j);
  up1.setString(j, "item"+j+" TINYINT(10)");
}
up1.executeQuery();

The error is

Parameter index out of range (2 > number of parameters, which is 1)

It occurs in the setString line during the second iteration


Solution

  • PreparedStatement can't be used for DDL queries like the CREATE TABLE in the question.

    The values passed to setString() get escaped in the resulting SQL, resulting in an invalid query sent to the database.

    When only the number of columns is given, just create the CREATE TABLE statement (use a StringBuilder as others suggested) and execute it with a plain Statement, no need for a PreparedStatement:

    String getCreateTableSql(int columns) {
      StringBuilder sql = new StringBuilder("CREATE TABLE IF NOT EXISTS itemset (");
      for (int i = 0; i < columns; i++) {
        if (i > 0) {
          sql.append(", ");
        }
        sql.append("item").append(i + 1).append(" TINYINT(10)");
      }
      sql.append(")");
      return sql.toString();
    }
    

    For 4 columns, this will output:

    CREATE TABLE IF NOT EXISTS itemset (item1 TINYINT(10), item2 TINYINT(10), item3 TINYINT(10), item4 TINYINT(10))