首页 > 解决方案 > 通过 JDBC PrepareStatement 将参数传递给 CREATE LOGIN 类型的 SQL 语句

问题描述

我有一条 SQL 语句create login user_bob with password = ?;。试图通过 JDBC PrepareStatement 将真实密码传递给语句。应该毫不意外地执行它。但不幸的是,出现错误,显示为“'@P0' 附近的语法不正确”。很想知道解决这个问题的方法。

我的代码如下所示:

String sql = "create login user_bob with password = ?;"
try (var conn = dataSource.getConnection()) {
    try (var stmt = conn.prepareStatement(sql)) {
        stmt.setString(1,  conf.getPwd());
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException("Fail to create logins, already rollback, caused by:", e);
    }
}

堆栈跟踪是:

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:265)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0'.

    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1662)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:615)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:537)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7417)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:3488)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:262)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:237)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:483)

标签: javasqlsql-serverjdbcprepared-statement

解决方案


推荐阅读