java - 如何使用 "source"命令运行脚本文件?

标签 java mysql

我正在编写一个连接到本地主机的应用程序。当应用程序首次运行时,我希望它使用以下方法初始化数据库:

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 查询语句。

http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html

您必须从代码中的文件加载 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/

相关文章:

php - 针对 1000000 多行优化此查询

java - throws 除了传播一个 checked Exception 之外还有其他作用吗?

java - java中如何将字符串转换为RegularTimePeriod?

Java - 取消同步函数上的排队调用

java - @EnableEurekaClient有什么用?

mysql - 如何在vb.net中备份mysql数据库

mysql - 我是否需要使用一个命令在 MySQL 触发器中开始结束?

java - 用java执行SQL脚本文件

php - SQLSTATE[HY093] : Invalid parameter number [string:Exception:private]

java - 无法通过序列化正确赋值