Incorrect syntax near '@P0'. exception whe

2019-08-15 19:43发布

问题:

I'm trying to create a Login and drop it using using Microsoft JDBC Driver.

CREATE LOGIN ? WITH PASSWORD = 'password'

and

DROP LOGIN ?

But I'm getting following exception in both cases.

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:332)
    at org.wso2.carbon.rssmanager.core.internal.manager.MSSQLRSSManager.attachUserToDatabase(MSSQLRSSManager.java:512)
    ... 57 more

I found similar questions in SO, but couldn't find an exact solution.

Please advice.

Thanks, Bhathiya

[update]

Here is my code snippet.

String sql = "CREATE LOGIN ? WITH PASSWORD = 'abc'";
stmt = conn.prepareStatement(sql);
stmt.setString(1, qualifiedUsername);
stmt.execute();

回答1:

You can't use ? in drop login statement (like in drop table, you cant write drop table ? - I'm facing the same problem just in that days!), you have to build statement with string concatenation in old fashion way.



回答2:

Using '?' is how your client code accepts parameters for statements. Most DDL statements like CREATE/ALTER/DROP do not accept parameters. When in doubt, you can always check the documentation of the statement, like CREATE LOGIN.

The solution is to build the statement dynamically and replace the login name in the statement itself, but be warned that doing so is subject to SQL injection problems and you must ensure your input is properly sanitized.