我不明白为什么或可能在这里出现语法错误。这是代码:

def dbname = "liberalgeek_wp"
def dbinfo = [url: 'jdbc:mysql://localhost:3306/mysql', user: dbuser, password: dbpass, driver: 'com.mysql.jdbc.Driver']
println("db info: ${dbinfo}\n\n")

def db = Sql.newInstance(dbinfo.url, dbinfo.user, dbinfo.password, dbinfo.driver)

def create_db_sql = "create database if not exists ${dbname}"
println("sql: ${create_db_sql}\n\n")
db.execute(create_db_sql)


这是我运行它时的输出:

db info: [url:jdbc:mysql://localhost:3306/mysql, user:kenny, password:xxxxxx, driver:com.mysql.jdbc.Driver]

sql: create database if not exists liberalgeek_wp

Mar 18, 2017 4:03:59 PM groovy.sql.Sql execute
WARNING: Failed to execute: create database if not exists ? because: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''liberalgeek_wp'' at line 1
Caught: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''liberalgeek_wp'' at line 1
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''liberalgeek_wp'' at line 1
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
    at setup_wordpress.createMySQLDatabase(setup_wordpress.groovy:125)


我无法想象该命令可能会出现什么语法错误,因此我打开了命令行,并使用了我的Groovy脚本使用的相同用户名/密码来登录mysql。我将命令复制/粘贴到mysql中,效果很好:

Kenny-iMac:~$ mysql -ukenny -p mysql
Enter password: xxxxxx

mysql> create database if not exists liberalgeek_wp;
Query OK, 1 row affected, 1 warning (0.00 sec)


怎么了?

最佳答案

您的问题是您尝试使用prepared statements执行此语句。但是,在准备好的语句中不允许使用DDL指令(例如create database),因为数据库名称不能绑定到变量。

在特定情况下,您可以执行以下操作:无需使用准备好的语句即可直接构建查询。

在这方面,我必须更加精确:实际上:在准备好的语句中允许使用DDL语句,但是您不能将变量绑定到诸如数据库,表或列名之类的名称。但是,您可以将变量绑定到其他内容,例如默认值,甚至可以设置参数值,尽管我没有对此进行测试。

10-06 01:18