Unable to create database using prepared statements in MySql

Tags: , , , ,



I am trying to create the database using a prepared statement in MySQL. Here I am passing the parameters as shown.

PreparedStatement createDbStatement = connection.prepareStatement("CREATE DATABASE ?");
createDbStatement.setString(1, "first_database");
createDbStatement.execute();
connection.commit();

But I am getting a syntax error. Is it possible to create tables and databases using prepared statements?

Answer

in a PreparedStatement can only be used to bind values (e.g., in where conditions on in values clauses), not object names. Therefore, you cannot use it to bind the name of a database.

You could use string manipulation to add the database name, but in this case, there’s really no benefit in using PreparedStatements, and you should just use a Statement instead:

String dbName = "first_database";
Statement createDbStatement = connection.createStatement();
createDbStatement.execute("CREATE DATABASE " + dbName);


Source: stackoverflow