Executing SQL with Eclipse using Apache Ant

2 September, 2007 (05:10) | Java, PHP

Today I needed an easy way to rebuild my database manually for a project I’m working on so I found out how to use the SQL Database integration in Apache Ant that ships with Eclipse, so I could build/rebuild my PostgreSQL databases quickly for development.

It’s pretty simple, these are the steps I took to do it:

1) Add an Ant Task to your build.xml file, here’s an example:

<target name="rebuild.database">
    <sql
        driver="org.postgresql.Driver"
        url="jdbc:postgresql://localhost/yourdatabase"
        userid="postgres"
        password="yourpassword"
        >
        <transaction src="path/to/your/sql/file.sql">
        <transaction src="path/to/your/other/sql/file.sql>

    </sql>
</target>

2) Install PostgreSQL JDBC Driver. On my system, I could install it with a simple command because I run Gentoo GNU/Linux on my workstation. Once it was emerged, it needed to be added to my classpath.

3) Add the driver to the class path. In Eclipse, right click your existing build.xml and select “Run As > 3 Ant Build…” and a configuration window will appear. Select the Classpath tab, and then click ‘User Entries’ at the top level. Click ‘Add External JARs’ button and select your PostgreSQL JDBC driver JAR file. Now you need to tell Ant which task to execute.

4) Click back to the Targets tab, remove the ticks in the othe targets and only select your database target.

5) Change the name at the top of the box to be something meaningful, ‘rebuild the database’ or something will do.

6) Click Apply, then Run.

7) Celebrate. You just got an extra 5 mins of productivity every day :)