1.在E盘下建立一个Access文件,命名为zhaochao.accdb,打开文件,创建一张USER表插入内容如下:
2.打开控制面板-->管理工具-->数据源(ODBC) 如下图所示:然后点击系统DSN-->添加-->选择Microsoft Access Driver(*.mbd,*.accdb);
3.单击完成后会显示下图:然后单击选择,选择E:/zhaochao.accdb文件,数据源名中填写zhaochao然后单击确定,配置好数据源。
4.eclipse或者myeclipse中新建java工程,工程中建立一个接口如下
- package com.zhaochao.dba;
- import java.sql.Connection;
- public interface iConn {
- Connection getConn();
- }
- package com.zhaochao.dba;
- import java.sql.Connection;
- import java.sql.DriverManager;
- public class AccessConn implements iConn {
- private static final String DBDRIVER = "sun.jdbc.odbc.JdbcOdbcDriver" ;
- private static final String DBURL = "jdbc:odbc:zhaochao" ;
- private static final String DBUSER = "" ;
- private static final String DBPASS = "";
- private Connection conn=null;
- @Override
- public Connection getConn() {
- // TODO Auto-generated method stub
- try{
- Class.forName(DBDRIVER);
- conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
- }catch(Exception e){
- e.printStackTrace();
- }
- return conn;
- }
- }
- package com.zhaochao.dba;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- // TestMySQL();
- // TestOracle();
- // TestDB2();
- // TestSQLServer();
- TestAccess();
- }
- private static void TestAccess() {
- Connection conn=null;
- PreparedStatement ps=null;
- ResultSet rs=null;
- iConn iconn=new AccessConn();
- conn=iconn.getConn();
- String sql="select * from USER";
- try {
- ps=conn.prepareStatement(sql);
- rs=ps.executeQuery();
- while(rs!=null &&rs.next()){
- System.out.println(rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(conn!=null){
- try {
- conn.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if(ps!=null){
- try {
- ps.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if(rs!=null){
- try {
- rs.close();
- } catch (Exception e2) {
- // TODO: handle exception
- e2.printStackTrace();
- }
- }
- }
- }
- }
7.运行结果如下:
- 1|zhaochao|zhaochao
- 2|admin|admin
http://blog.csdn.net/whzhaochao/article/details/12838221