Java 访问access数据库

  1. 创建数据源
    执行 C:\Windows\System32\odbcad32.exe
    参考:https://www.cnblogs.com/BelieveFish/p/10275320.html
  2. 添加 jdbc.jar
    参考:https://blog.csdn.net/qq_42839596/article/details/104718836
  3. 代码
package com.boyilida.psom.collect.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.*;
import java.util.*;

@Component
public class AccessUtils {

    public static boolean DEBUG;// 是否开启调试
    public static String ACCESS_DB_NAME;// access数据源名称
    public static String ACCESS_CHARSET;// access字符集

    @Value("${access.debug}")
    private boolean debugFlag;

    @Value("${access.dbname}")
    private String dbnameFlag;

    @Value("${access.charset}")
    private String charsetFlag;

    @PostConstruct
    public void init() {
        DEBUG = debugFlag;
        ACCESS_DB_NAME = dbnameFlag;
        ACCESS_CHARSET = charsetFlag;
    }

    /**
     * 查询
     */
    public static List<Map<String, Object>> executeQuery(String username, String password, String sql) {
        List<Map<String, Object>> res = new ArrayList<>();

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            long start = System.currentTimeMillis();
            conn = getConnection2(username, password);
            stmt = conn.createStatement();
            // 读取表的内容
            rs = stmt.executeQuery(sql);
            ResultSetMetaData data = rs.getMetaData();
            int count = 0;
            while (rs.next()) {
                count++;
                Map<String, Object> map = new LinkedHashMap<>();
                for (int i = 1; i <= data.getColumnCount(); i++) {
                    // 获取别名
                    map.put(data.getColumnLabel(i), rs.getObject(i));
                }
                res.add(map);
            }
            if (AccessUtils.DEBUG) {
                System.out.println("查询出结果数量:" + count + ",耗时:" + (System.currentTimeMillis() - start) + " ms");
                System.out.println("==================================end");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            releaseConnection(rs, stmt, conn);
        }
        return res;
    }

    /**
     * 获取连结2
     */
    public static Connection getConnection2(String username, String password) {
        try {
            long start = System.currentTimeMillis();
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String url = "jdbc:odbc:" + ACCESS_DB_NAME;//databaseName就是刚刚添加的数据源名称
            //Access中的数据库默认编码为GBK,本地项目为UTF-8,若不转码会出现乱码
            Properties p = new Properties();
            p.put("charSet", ACCESS_CHARSET);
            p.put("username", username);
            p.put("password", password);
            Connection conn = DriverManager.getConnection(url, p);//没有用户名和密码的时候直接为空
            if (AccessUtils.DEBUG) {
                System.out.println("成功获取连接,耗时:" + (System.currentTimeMillis() - start) + " ms");
            }
            return conn;
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放连接
     */
    public static void releaseConnection(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}


server:
  port: 82

access:
  debug: true
  dbname: databaseName
  charset: GBK

  1. 部署时发现的问题
    4.1 创建数据源时,运行 System32 下的 odbcad32.exe 并没有找到 access 数据库的 Driver,这是因为电脑安装的是 32 位的 office,这时需要运行 C:\Windows\SysWOW64\odbcad32.exe
    4.2 运行 32 位的 odbcad32.exe,创建好数据源后,连接数据报错 java.lang.RuntimeException: java.sql.SQLException: [Microsoft][ODBC 驱动程序管理器] 在指定的 DSN 中,驱动程序和应用程序之间的体系结构不匹配] with root cause,这是因为 jre 使用的是 64 位的

    4.3 换成 32 位的 jre,启动时报错,因为设置了 -Xms2g -Xmx2g,具体原因参考 https://www.cnblogs.com/qiumingcheng/p/7364777.html ,修改为 -Xms1g -Xmx1g,成功启动,功能一切正常
posted @ 2023-03-16 20:45  君子键  阅读(292)  评论(0)    收藏  举报