Skip to content
Advertisement

Unable to create database using prepared statements in MySql

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?

Advertisement

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement