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?
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 PreparedStatement
s, and you should just use a Statement
instead:
String dbName = "first_database";
Statement createDbStatement = connection.createStatement();
createDbStatement.execute("CREATE DATABASE " + dbName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With