Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a script to create tables with HSQLDB

Tags:

java

sql

hsqldb

I use hsqldb to run my unit tests that need a database access.

For the moment, when I want to create a table for a specific test, I have the following code:

private void createTable() {
    PreparedStatement ps;
    try {
        ps = getConnection().prepareStatement("CREATE TABLE T_DATE (ID NUMERIC PRIMARY KEY, DATEID TIMESTAMP)");
        ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The getConnection() method retrieve a DataSource defined in a Spring context:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <property name="url" value="jdbc:hsqldb:mem:memoryDB"/>
    <property name="username" value="SA"/>
    <property name="password" value=""/>
</bean>

Now, I want to create my table from a SQL script (of course, this script will contain more than one table creation):

CREATE TABLE T_DATE_FOO (ID NUMERIC PRIMARY KEY, DATEID TIMESTAMP);
CREATE TABLE T_DATE_BAR (ID NUMERIC PRIMARY KEY, DATEID TIMESTAMP);
...

I've seen in the HSQLDB documentation that I can ask him to run a script at the startup. However, it does not meet my requirements, as I want to run a script at the runtime.

Of course, I can read the file myself, and for every SQL statement, I run a ps.executeUpdate() command, but I don't want to use this kind of solution (except if there are no other solution).

Any idea?

like image 767
Romain Linsolas Avatar asked Feb 19 '10 10:02

Romain Linsolas


People also ask

How do I connect to HSQLDB in-memory?

Because we started an in-memory instance the connection url is a memory database url that looks like jdbc:hsqldb:mem:instanceName You will not be able to connect using this url because neither the host and the port are available, instead you should use a server database url that looks like jdbc:hsqldb:hsql://host:port/ ...


1 Answers

You might give org.hsqldb.util.SqlFile a try. This class seems to be a perfect match for your problem.

like image 53
Ralf Huthmann Avatar answered Nov 14 '22 21:11

Ralf Huthmann