Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
Deepak Ram Avatar asked Oct 27 '14 07:10

Deepak Ram


1 Answers

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);
like image 118
Mureinik Avatar answered Oct 16 '22 09:10

Mureinik