最新消息:发现真没时间折腾VPS,最近又换了个空间。呵呵

Java通过JDBC和ODBC桥接来访问Access文件

这次做的系统有输入和输出为MDB(Access)文件,在网上找了一下,可以用JDBC和ODBC桥接来实现Access文件的访问。测试代码如下:

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {

    static Connection connection;
    static Statement statement;

    public static void main(String[] args) {

        String mdbFile = "C:\TEST.mdb";

        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + mdbFile;
            connection = DriverManager.getConnection( database ,"","");

            buildStatement();
            executeQuery();

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void buildStatement() throws SQLException {
        statement = connection.createStatement();
    }

    public static void executeQuery() throws SQLException {
        boolean foundResults = statement.execute("SELECT * FROM TEST");
        if (foundResults) {
            ResultSet set = statement.getResultSet();
            if(set != null) displayResults(set);
        } else {
            connection.close();
        }
    }

    public static void displayResults(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int columns = metaData.getColumnCount();
        StringBuilder text = new StringBuilder();

        while (rs.next()) {
            for (int i = 1; i <= columns; ++i) {
                text.append(metaData.getColumnName(i));
                text.append(":t");
                text.append(rs.getString(i));
                text.append(" n");
            }
            text.append(" n");
        }

        System.out.println(text.toString());
    }
}

转载请注明:宇托的狗窝 » Java通过JDBC和ODBC桥接来访问Access文件

发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址