你的位置:首页 > Java教程

[Java教程]Win 10 ODBC DataSource添加Access数据库并使用Java JDBC访问

ODBC DataSource添加Access数据库

  1. 进入Control Panel->System and Security->Administrative Tools->ODBC Data Sources (64-bit)(根据访问数据库的application位数版本决定使用多少位版本数据源)
  2. 在System DSN(Data Source Name)下添加,选择Microsoft Access Driver,填写DataSource Name,Select一个Access数据库,OK确定即可。也可以点击Advanced设置login name和password,也可以不设置

Java JDBC访问Access数据库

以下为封装好的DBApplication类

public class DBApplication{ public Connection conn = null; public ResultSet rs = null; private String databaseDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; private String databaseConnStr = "jdbc:odbc:DS"; //注意连接字符串最后部分应该为之前设置的DataSource Name而不是Database Name private String userName = "tianzhi"; //如果之前没有设置用户名和密码就为空 private String passWord = "***"; public DBApplication(){     
try{ Class.forName(databaseDriver); } catch(java.lang.ClassNotFoundException e){ System.err.println("加载驱动器有错误:" + e.getMessage()); } } public int executeInsert(String sql){ int num = 0; try{ conn = DriverManager.getConnection(databaseConnStr,userName, passWord); Statement stmt = conn.createStatement(); num = stmt.executeUpdate(sql); } catch(SQLException ex){ System.err.println("执行插入有错误:" + ex.getMessage()); } closeDataBase(); return num; } public ResultSet executeQuery(String sql){ rs = null; try{ conn = DriverManager.getConnection(databaseConnStr,userName, passWord); Statement stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch(SQLException ex){ System.err.println("执行查询有错误:" + ex.getMessage() + sql); } return rs; } public int executeDelete(String sql) { int num = 0; try{ conn = DriverManager.getConnection(databaseConnStr,userName, passWord); Statement stmt = conn.createStatement(); num = stmt.executeUpdate(sql); } catch(SQLException ex){ System.err.println("执行删除有错误:" + ex.getMessage()); } closeDataBase(); return num; } public void closeDataBase(){ try{ conn.close(); } catch(Exception end){ System.err.println("执行关闭Connection对象有错误:" + end.getMessage()); } }}