我正在尝试编写一个将mysql转储导入数据库的函数。我的代码如下所示:
def sout = new StringBuffer()
def serr = new StringBuffer()
String pathToDump = "C:\\Users\\Lojza\\AppData\\Local\\Temp\\protetika-dump-temp-13393134598714336471323836046295.sql"
def process = "mysql --host=localhost --user=protetika --password=protetika --port=3306 --default-character-set=utf8 < \"${pathToDump}\" ".execute()
process.consumeProcessOutput(sout, serr)
process.waitForOrKill(10000)
println 'sout: ' + sout // => test text
println 'serr: ' + serr
我在Grails控制台中尝试了这段代码,但它返回了我:
mysql Ver 14.14 Distrib 5.5.21, for Win64 (x86)
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Usage: mysql [OPTIONS] [database]
-?, --help Display this help and exit.
...... (and many more lines)
我无法弄清楚上面的代码有什么问题...当我尝试在cmd中执行生成的生产线时,它可以工作并导入数据库。我执行的命令如下所示:
mysql --host=localhost --user=protetika --password=protetika --port=3306 --default-character-set=utf8 < "C:\Users\Lojza\AppData\Local\Temp\protetika-dump-temp-13393134598714336471323836046295.sql"
感谢您的帮助!
此致
Lojza
答案 0 :(得分:1)
重定向在Java下的工作方式与在Windows命令提示符下的工作方式不同。解决此问题的方法是使用-e选项执行source命令以读取文件。所以从命令行可以做到
mysql --host=localhost --user=protetika --password=protetika --port=3306 --default-character-set=utf8 –e “source C:\Users\Lojza\AppData\Local\Temp\protetika-dump-temp-13393134598714336471323836046295.sql"
从groovy(未经测试)
执行此操作的代码def process = "mysql --host=localhost --user=protetika --password=protetika --port=3306 --default-character-set=utf8 -e \"source "${pathToDump}\"\" ".execute()