如何使用PreparedStatement切换数据库(担心sql注入)?

时间:2015-06-03 06:41:42

标签: sql sql-server

我有一个与sql server通信的简单jdbc应用程序。

我可以使用"使用databaseName"在PreparedStatement中。

void useDatabase(Statement statement, String databaseName) throws SQLException {

    //This works but I was worried about sql injection as 
    //databaseName is provided by the user.
    //statement.executeUpdate("use \"" + databaseName + "\"");


    //So I tried this but I am 
    //Getting com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0'.
    PreparedStatement preparedStatement = statement.getConnection().prepareStatement("use ?");
    preparedStatement.setString(1, databaseName);
    preparedStatement.executeUpdate();
} 

使用关键字文档: https://technet.microsoft.com/en-us/library/ms188366.aspx

0 个答案:

没有答案