7

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?

1 Answer 1

14

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Nice answer, but i have a question; Should dbName be validated here manually?
This is a "skeleton" answer - you should probably add some input sanity/validation here if you get the dbName from user input.
I know, I just wondered if Statement.execute() method does any validation for the input query; or it just sends the query without any validation. Thanks.
It just sends it to the databsae

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.