我不明白为什么或如何在这里获得语法错误。这是代码:
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)
出了什么问题?
答案 0 :(得分:1)
您的问题是您尝试使用prepared statements
执行此语句。但是,在预准备语句中不允许使用DDL指令(例如create database),因为数据库名称不能绑定到变量。
在特定情况下您可以做什么:直接构建查询而不使用预准备语句。
我必须更准确地说:实际上:在准备好的语句中允许使用DDL语句 ,但是你不能将变量绑定到诸如数据库,表或列名称。但是,您可以将变量绑定到其他内容,例如默认值或甚至设置参数值,尽管我没有测试过。
答案 1 :(得分:1)
使用executeUpdate而不是执行并且不在调用中使用GString,在此之前解析字符串,认为这是为了防止SQL注入。
....
def create_db_sql = 'create database if not exists ' + dbname
println("sql: ${create_db_sql}\n\n")
db.executeUpdate( create_db_sql )
....
使用MySQL 5.7.17版进行测试