Java8 连接Access数据库—UCanAccess 方式介绍
- Java8 中JDK1.8中不再包含access桥接驱动,因此不再支持jdbcodbc桥接方式。
- 解决方法:
- 1.java Access JDBC jar包:Access_JDBC30.jar使用导入数据库相应的jar包,进行连接。
- 2.UCanAccess是一个Microsoft Access的开源JDBC驱动实现
- 支持 Access 2000、2003、2007、2010 及后续高版本
- 支持 SELECT, INSERT,UPDATE,DELETE 语句。 事务和savepoints。
- 支持数据类型:YESNO,BYTE,INTEGER,LONG,SINGLE,DOUBLE,NUMERIC,CURRENCY,COUNTER,TEXT,OLE,MEMO,GUID,DATETIME。
- 支持多用户并发访问。
- 支持连接池。
- 支持MS Access SQL。
- 限制:
- maven配置:
<!--AccessDB 数据库 驱动-->
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.1</version>
</dependency>
package com.hyman.date0702_0708.accessdb;
import java.sql.*;
/**
* @program: javalearning
* @Date: 2018/7/11 11:03
* @Author: hyman.hu
* @Description: 工具类
*/
public class AccessDBUtils {
private static final String dbURL = "jdbc:ucanaccess://" +
"C:\\Users\\skysoft\\Desktop\\天软物料管理系统\\hyman.accdb";
/*
* 加载驱动
*/
static {
try {
// Step 1: Loading or registering Oracle JDBC driver class
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch (ClassNotFoundException cnfex) {
System.out.println("Problem in loading or registering MS Access JDBC driver");
cnfex.printStackTrace();
}
}
//建立连接
public static Connection getConn() {
try {
// Step 2: Opening database connection
// Step 2.A: Create and get connection using DriverManager class
return DriverManager.getConnection(dbURL);
} catch (Exception e) {
System.out.println("AccessDB connection fail");
e.printStackTrace();
}
return null;
}
// 关闭资源
public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null)
rs.close();// 这里出现异常了,rs关闭了吗?,如果没有怎么解决,ps , con也是一样的。
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package com.hyman.date0702_0708.accessdb;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @program: javalearning
* @Date: 2018/7/11 13:56
* @Author: hyman.hu
* @Description: DB工具类
*/
public class DBUtils {
/**
* 增加、删除、改
*
* @param sql sql
* @param params 参数
* @return 添加结果
*/
public static boolean update(String sql, List<Object> params) throws SQLException {
int result = -1;
Connection conn = null;
PreparedStatement ps = null;
try {
conn = AccessDBUtils.getConn();
assert conn != null;//直接抛异常
ps = conn.prepareStatement(sql);
int index = 1;
if (params != null && !params.isEmpty()) {
for (Object param : params) {
ps.setObject(index++, param);
}
}
result = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
try {
assert conn != null;
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
throw e;
} finally {
AccessDBUtils.close(conn, ps, null);
}
return result > 0;
}
/**
* 查询多条记录
*
* @param sql sql
* @param params 参数
* @return 查询结果
*/
public static List<Map<String, Object>> select(String sql, List<Object> params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<>();
int index = 1;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = AccessDBUtils.getConn();
assert conn != null;
ps = conn.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (Object param : params) {
ps.setObject(index++, param);
}
}
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int col_len = metaData.getColumnCount();
Map<String, Object> map = null;
while (rs.next()) {
map = new HashMap<>();
for (int i = 0; i < col_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = rs.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
AccessDBUtils.close(conn, ps, rs);
}
return list;
}
/**
* 通过反射机制查询多条记录
*
* @param sql sql
* @param params 参数
* @param clazz 类
* @return 查询结果
*/
public static <T> List<T> select(String sql, List<Object> params,
Class<T> clazz) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
List<T> list = new ArrayList<>();
int index = 1;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = AccessDBUtils.getConn();
assert conn != null;
ps = conn.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (Object param : params) {
ps.setObject(index++, param);
}
}
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int cols_len = metaData.getColumnCount();
T t;
while (rs.next()) {
//通过反射机制创建一个实例
t = clazz.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = rs.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
Field field = clazz.getDeclaredField(cols_name);//获取对象属性
field.setAccessible(true); //打开javabean的访问权限
field.set(t, cols_value);
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
AccessDBUtils.close(conn, ps, rs);
}
return list;
}
}
package com.hyman.date0702_0708.accessdb;
/**
* @program: javalearning
* @Date: 2018/7/11 14:23
* @Author: hyman.hu
* @Description:
*/
public class User {
private Integer userId;
private String userName;
private String email;
private Integer age;
public User() {
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
package com.hyman.date0702_0708.accessdb;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @program: javalearning
* @Date: 2018/7/11 11:36
* @Author: hyman.hu
* @Description: 测试类
*/
public class TestClass {
public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {
// List<User> list = DBUtils.select("select * from User",null,User.class);
// System.out.println(list);
String sql = "insert into User (userName,email,age) values (?,?,?)";
List<Object> list = new ArrayList<>();
list.add("andy");
list.add("andy.zhu@cdskysoft.com");
list.add(29);
System.out.println(DBUtils.update(sql,list));
}
}