Monday, September 22, 2008

Accessing DBF and MDB files

I was tasked to interface with some legacy systems and they were written in Visual FoxPro. Essentially my Java code has to select and insert records from/into DBF files. I started to search for 3rd party Java libraries but then I thought "Microsoft has perfectly good drivers for Visual FoxPro. Why not use them?" Even though these are ODBC drivers, I can "bridge" them using the JDBC-ODBC bridge.

The solution became very simple - as long as you figure out the correct URL:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection conn = java.sql.DriverManager.getConnection(
"jdbc:odbc:DRIVER={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=C:/",
"admin", "");

To figure out the URL, I created File DSNs using the ODBC Data Source console and then looked at the files under
C:\Program Files\Common Files\ODBC\Data Sources

Similar setups can be used for Microsoft Access MDB files. The URL is:
Jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\test\test.mdb

No comments: