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
PreparedStatementcan’t be used for DDL queries like theCREATE TABLEin 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
StringBuilderas others suggested) and execute it with a plainStatement, no need for aPreparedStatement:For 4 columns, this will output:
CREATE TABLE IF NOT EXISTS itemset (item1 TINYINT(10), item2 TINYINT(10), item3 TINYINT(10), item4 TINYINT(10))