【问题标题】:Load data from file when initializing data in H2在 H2 中初始化数据时从文件中加载数据
【发布时间】:2018-10-29 16:43:11
【问题描述】:

我有一个大的 data.sql 文件,用于在应用程序启动时将数据加载到 H2 中。

这是我的 data.sql 的一部分

CREATE TRIGGER AU_TRIGGER
AFTER UPDATE ON TABLE_A FOR EACH ROW
CALL "com.trigger.MyTrigger";

LOAD DATA LOW_PRIORITY INFILE 'C:/Users/mytextfile.delim'
REPLACE INTO TABLE TABLE_B
FIELDS TERMINATED BY '|'
IGNORE 1 LINES
(name, age, etc);

当我启动应用程序时,data.sql 中的所有查询都运行良好,但一旦到达LOAD DATA... 部分,我就会收到此错误:

原因:org.h2.jdbc.JdbcSQLException: SQL 语句中的语法错误“LOAD[*] DATA LOW_PRIORITY INFILE ... [42000-197]

This is my application.yml spring.datasource.url
=jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
spring.datasource.username: myusername
spring.datasource.password: mypassword
driver-class-name: org.h2.Driver

谁能建议我如何解决这个问题?有什么提示吗?

【问题讨论】:

标签: mysql h2


【解决方案1】:

我能够通过以编程方式配置 H2 来解决这个问题。

@Bean
public DataSource dataSource() throws SQLException {        
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    EmbeddedDatabase db = builder
            .setType(EmbeddedDatabaseType.H2)
            .setName("mydb;MODE=MYSQL")
            .addScript("mariadb.sql") //this file name has to be different than data.sql otherwise Springboot will pick data.sql automatically and this will also run.
            .build();       
    return db;
}

然后创建另一个依赖于上述数据源的bean:

@Bean
@DependsOn("dataSource")
public Void string(DataSource db) throws SQLException {
    //read file using whatever means. I used Scanner and delimeted it myself. 
    final Connection connection = db.getConnection();
    //here use the prepratedStatements 
    PreparedStatement stmt = connection.prepareStatement(Insert xyz); //lookup how to use PreparedStatement. 
    }

创建一个单独的 bean 将数据插入到表中是很重要的。您也可以在 DataSource bean 中运行准备好的语句,但它对我不起作用。所以我在 DataSource 全部设置后插入了它之外的数据。

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 2018-09-05
    • 2018-03-22
    • 2018-04-16
    • 2021-11-30
    • 2021-10-06
    • 2012-01-04
    • 1970-01-01
    • 2012-11-24
    相关资源
    最近更新 更多