package com.hy.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* ACCESS跨平台访问工具类
* @author HeYing 2014-11-4 下午5:34:39
*
*/
public class AccessDbUtils {
/**
* ACCESS数据库文件保存路径
*/
public static final String DBF_FILE_PATH = "/database/aftn.mdb";
private Connection conn;
private static AccessDbUtils instance;
private AccessDbUtils(){}
/**
* 获取实例
* @return
*/
public static AccessDbUtils getInstance(){
if(instance == null){
instance = new AccessDbUtils();
}
return instance;
}
/**
* 获得项目的根路径
* @return
*/
public static String getServerRoot(){
String webInfo = "/bin/";
String webRoot = "/WebRoot";
String path = AccessDbUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// System.out.println("path="+path);
if(path != null){
int index = path.indexOf(webInfo);
if(index != -1){
path = path.substring(0, index);
}
}
path = path.replace(webRoot, "");
if(path != null){
path = path.replace("%20", " ");
}
// System.out.println("path="+path);
return path;
}
/**
* 此方法只能在windows平台使用
* 获取连接
* @return
*/
public Connection getConnection(){
String mdbFile = getServerRoot() + DBF_FILE_PATH;
mdbFile = mdbFile.substring(1);
String dbUr1 = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + mdbFile;
System.out.println(dbUr1);
String user = "";
String password = "";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(dbUr1, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 适合于windows、Linux、Unix平台
* 获取连接
* @return
*/
public synchronized Connection getConnectionHXTT(){
String mdbFile = getServerRoot() + DBF_FILE_PATH;
mdbFile = mdbFile.substring(1);
String dbUr1 = "jdbc:access:////" + mdbFile;
System.out.println("dbUr1="+dbUr1);
String user = "";
String password = "";
try {
Class.forName("com.hxtt.sql.access.AccessDriver").newInstance();
conn = DriverManager.getConnection(dbUr1, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}