Can't create database using prepared statements in MySql

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

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

      

But I am getting syntax error. Can I create tables and databases using prepared statements? If not, please suggest an alternative approach.

+3


source to share


1 answer


c PreparedStatement

can only be used to bind values ​​(for example, c where

to c conditions values

), not object names. Therefore, you cannot use it to bind the database name.

You can use string manipulation to append the database name, but in this case there is no benefit to using PreparedStatement

s and you should just use Statement

instead:



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

      

+6


source







All Articles