简体   繁体   English

HSQLDB over JDBC:批量执行SQL语句

[英]HSQLDB over JDBC: execute SQL statements in batch

I need to initialize a database from my Java application. 我需要从我的Java应用程序初始化数据库。 For reasons of code maintainability, I would like to maintain the SQL code separately from the Java code (it is currently in a separate source file). 出于代码可维护性的原因,我想将SQL代码与Java代码分开维护(它目前在一个单独的源文件中)。

The first few lines of the file are as follows: 该文件的前几行如下:

-- 1 - Countries - COUNTRIES.DAT;
drop table Countries if exists;
create table Countries(
  CID integer,
  ECC varchar(2),
  CCD varchar(1),
  NAME varchar(50));

I read the SQL code from the file and store it in a string. 我从文件中读取SQL代码并将其存储在字符串中。 Then I do: 然后我做:

PreparedStatement stmt = dbConnection.prepareStatement(sqlString);

This fails with the following exception: 这失败,出现以下异常:

java.sql.SQLSyntaxErrorException: unexpected token: CREATE : line: 2

This looks as if JDBC doesn't like multiple SQL statements in a single PreparedStatement . 这看起来好像JDBC不喜欢单个PreparedStatement多个SQL语句。 I have also tried CallableStatement and prepareCall() , with the same result. 我也尝试过CallableStatementprepareCall() ,结果相同。

Does JDBC provide a way to pass the entire SQL script in one go? JDBC是否提供了一次性传递整个SQL脚本的方法?

The JDBC standard (and the SQL standard for that matter) assumes a single statement per execute. JDBC标准(以及该标准的SQL标准)假定每个执行一个语句。 Some drivers have an option to allow execution of multiple statements in one execute, but technically that option violates the JDBC standard. 某些驱动程序可以选择允许在一次执行中执行多个语句,但从技术上讲,该选项违反了JDBC标准。 There is nothing in JDBC itself that supports multi-statement script execution. JDBC本身没有任何内容支持多语句脚本执行。

You need to separate the statements yourself (on the ; ), and execute them individually, or find a third-party tool that does this for you (eg MyBatis ScriptRunner ). 您需要自己分离语句(在; ),并单独执行它们,或者找到为您执行此操作的第三方工具(例如MyBatis ScriptRunner )。

You might also want to look at something like flyway or liquibase. 您可能还想看一下像flyway或liquibase这样的东西。

To run a hardcoded / loaded from file queries you can use execute like: 要运行硬编码/加载的文件查询,您可以使用如下执行

Statement stmt = null;
String query = "drop table Countries if exists;
                create table Countries(
                      CID integer,
                      ECC varchar(2),
                      CCD varchar(1),
                      NAME varchar(50));";
try {
    stmt = con.createStatement();
    stmt.execute(query);
} catch (SQLException e ) {
    JDBCTutorialUtilities.printSQLException(e);
} finally {
    if (stmt != null) { stmt.close(); }
}

If you want to run dynamic queries for example to append values you have to use PreparedStatement. 如果要运行动态查询,例如附加值,则必须使用PreparedStatement。 For running a query from a file it's not recommended to put dynamic queries in it. 要从文件运行查询,建议不要在其中放置动态查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM