JDBC PrepareStatement 参数不适用于 CREATE、DROP、ALTER

JDBC PrepareStatement parameters do not work for CREATE, DROP, ALTER

我需要使用 JDBC 创建一个新的 Oracle 用户。新用户的用户名和密码由用户通过 GUI 提供。以下代码工作正常(我也可以使用 Statement 而不是 PreparedStatement)。

PreparedStatement preparedStatement = connection.prepareStatement("create user " + username + " identified by " + password);
preparedStatement.execute();

但是,由于用户名和密码是由用户提供的,其中可能包含space、分号、引号等特殊字符,可能导致上述声明无效。我不希望我的代码对用户名和密码进行验证,并将其留给 Oracle 进行验证。因此,我想到了使用prepared statement中的参数来代替:

PreparedStatement preparedStatement = connection.prepareStatement("create user ? identified by ?");
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
preparedStatement.execute();

但是根本不起作用。当我提供有效的用户名和密码时,我将得到 "ORA-01935: missing user or role name"。这些参数似乎不适用于 CREATE、DROP、ALTER 语句。如何解决我的问题?提前致谢。

用户名和密码不是文本值,而是标识符

PreparedStatement 参数标记 (?) 用于提供各种数据类型的动态值。它们不能用于提供标识符,例如您不能像 SELECT * FROM ? 那样动态指定 table 名称。

字符串连接是唯一的方法,如果标识符包含特殊字符,则需要引用 (") 标识符,就像 documentation says:

If a password starts with a non-alphabetic character, or contains a character other than an alphanumeric character, the underscore (_), dollar sign ($), or pound sign (#), then it must be enclosed in double quotation marks. Otherwise, enclosing a password in double quotation marks is optional.