javajdbcspotbugs

Is there a way to create a database using java jdbc driver without having a danger of SQL injection attack


I want to creata a database in mysql using a code snippet similar to the following using java

Statement statement = connection.createStatement();
String query = String.format(C"REATE DATABASE %s" , database);
statement.executeUpdate(query);

But spotbugs gives passes a nonconstant String to an execute or addBatch method on an SQL statement error. When tried to create a prepared statement using the query, it give the error A prepared statement is generated from a nonconstant String.

StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("CREATE DATABASE ");
stringBuilder.append(database);
try (PreparedStatement preparedStatement = connection.prepareStatement(stringBuilder.toString())) {
    preparedStatement.executeUpdate();
}

Is there any other way to create a query in java?


Solution

  • You'll need to verify the validity of the data passed to your SQL prior to passing it.

    For a create database statement that's pretty simple as it'll have to be a single word that's not a reserved word in SQL (and more specifically the SQL dialect your database is using, there are differences between dialects).

    So basically you're going to have to do the same checks in code you'd do in your head when coming up with a database name when executing the statement manually using the SQL console commands.