Java PreparedStatement在execute()上抱怨SQL语法

Mik*_*ike 3 java mysql syntax jdbc prepared-statement

这让我疯了......我在这里做错了什么?

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();
}
Run Code Online (Sandbox Code Playgroud)

结果是...

02:59:12,885 ERROR [STDERR] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:SQL语法中有错误; 查看与您的MySQL服务器版本对应的手册,以便在第1行的''password'varchar(100)'附近使用正确的语法

但...

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();
}
Run Code Online (Sandbox Code Playgroud)

完美地工作......所以直接将文本直接输入MySQL命令行客户端.

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

我究竟做错了什么?

dog*_*ane 9

MySQL手册明确表示,?(参数标记)是唯一,不列名绑定的数据值.

参数标记只能用于应出现数据值的位置,而不能用于SQL关键字,标识符等.

所以你必须使用你的第二种方法.