简体   繁体   English

无法在 MySql 中使用准备好的语句创建数据库

[英]Unable to create database using prepared statements in MySql

I am trying to create the database using a prepared statement in MySQL.我正在尝试使用 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 (eg, in where conditions on in values clauses), not object names.PreparedStatement中只能用于绑定值(例如,在values子句中的where条件中),而不是对象名称。 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:您可以使用字符串操作来添加数据库名称,但在这种情况下,使用PreparedStatement确实没有任何好处,您应该只使用Statement来代替:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM