Java PreparedStatement complains about SQL syntax while executing ()

It drives me crazy ... What am I doing wrong here?

ArrayList<String> toAdd = new ArrayList<String>();
toAdd.add("password");
try{
    PreparedStatement pStmt = conn.prepareStatement("ALTER TABLE testTable ADD ? varchar(100)");
        for (String s : toAdd) {
            pStmt.setString(1, s);
            pStmt.execute();
        }
} catch (SQLException e) {
    e.printStackTrace();
}

Results in ...

02: 59: 12,885 ERROR [STDERR] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in the SQL syntax; check the manual that matches your version of MySQL server for the correct syntax to use next to '' password 'varchar (100)' on line 1

but...

ArrayList<String> toAdd = new ArrayList<String>();
toAdd.add("password");
try{
    Statement stmt = conn.prepareStatement();
        for (String s : toAdd) {
            stmt.execute("ALTER TABLE testTable ADD "+s+" varchar(100)");
        }
} catch (SQLException e) {
    e.printStackTrace();
}

works fine ... So it directly injects text directly into the MySQL command line client.

mysql> alter table testTable add stringGoesHere varchar(100);
Query OK, 1 row affected (0.23 sec)
Records: 1  Duplicates: 0  Warnings: 0

What am I doing wrong?

+3
source share
6 answers

MySQL , ? ( ) , .

, SQL, .. .

, .

+9

JDBC , , , . . . , .

+1

, . , , , , ..

+1

. "ALTER TABLE testTable ADD\'" + s + "\' varchar (100)". .

.

+1

ALTER TABLE, .

, DDL Java PreparedStatement.

-1

pStmt.executeUpdate();

pStmt.close();

-1

All Articles