我正在编写一个连接到本地主机的应用程序。当应用程序首次运行时,我希望它使用以下方法初始化数据库:
public void initDataBase() {
try {
Statement stm = con.createStatement();
stm.executeQuery("source shippingSQLscript.sql");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
其中shippingSQLscript.sql包含插入所有数据的正确sql语句。但是,当我运行它时,该方法会抛出:
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 'source shippingSQLscript.sql'
at line 1
我也尝试过使用stm.execute()
,但得到了相同的结果。
最佳答案
您无法使用 JDBC 驱动程序执行此操作。 source
只是MySQL命令行工具支持的命令。请参阅此处:
http://forums.mysql.com/read.php?39,406094,406329#msg-406329
这是命令行工具的命令列表。大多数不支持 JDBC 查询语句。
您必须从代码中的文件加载 SQL 命令并将它们发送到 JDBC 执行方法。像这样的东西:
Statement stm = con.createStatement();
BufferedReader reader = new BufferedReader(new FileReader(new File(...)));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
// this is the trick -- you need to pass different SQL to different methods
if (line.startsWith("SELECT")) {
stm.executeQuery(line);
} else if (line.startsWith("UPDATE") || line.startsWith("INSERT")
|| line.startsWith("DELETE")) {
stm.executeUpdate(line);
} else {
stm.execute(line);
}
}
stm.close();
关于java - 如何使用 "source"命令运行脚本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437240/