本文介绍了如何使用“源"运行脚本文件?命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am coding an application that connects to a localhost. When the application first runs I want it to initialize the Database using this method:

public void initDataBase() {
    try {
        Statement stm = con.createStatement();
        stm.executeQuery("source shippingSQLscript.sql");
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

其中shippingSQLscript.sql 包含正确的sql 语句以插入所有数据.但是,当我运行它时,该方法会抛出:

Where shippingSQLscript.sql contains the correct sql statements to insert all the data. However when I run it the method throws:

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() 但结果相同.

I have tried using stm.execute() as well but have had the same result.

推荐答案

您无法使用 JDBC 驱动程序执行此操作.source 只是 MySQL 命令行工具支持的一个命令.看这里:

You cannot do this with the JDBC driver. source is only a command supported by the MySQL command line tool. See here:

http://forums.mysql.com/read.php?39,406094,406329#msg-406329

这是命令行工具的命令列表.大多数支持作为 JDBC 查询语句.

Here's the list of commands for the command-line tool. Most are not supported as JDBC query statements.

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

您必须从代码中的文件加载 SQL 命令,并将它们发送到 JDBC 执行方法.类似的东西:

You will have to load your SQL commands from the file in your code and send them to JDBC execute methods. Something like:

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();

这篇关于如何使用“源"运行脚本文件?命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 22:34