在java中联接Access中多采用jdbc-odbc的方式,传统做法是在 windows系统下的管理工具里分建一个数据源指向Access数据厍文件。
这样建立的应用程序加大了布属难度。要解决这个问题可以像其它(例如:VB,Delphi等)IDE那样用自建数据源(也称动态数据源)来完成。
联系方法如下:
public class faq
{
String sDBDriver;
String sConnStr;
Connection conn;
ResultSet rs;
/**
* 初始化联接
*/
public faq(){
String dbc = getFilePathRoot()+”/jspshop/database/db.mdb”;
sDBDriver = “sun.jdbc.odbc.JdbcOdbcDriver”;
sConnStr = “jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=”+dbc;
conn = null;
rs = null;
try{
Class.forName(sDBDriver);
}catch(ClassNotFoundException classnotfoundexception){
System.err.println(”faq(): ” + classnotfoundexception.getMessage());
}
}
/**
* 联接构建好后使用方法就和其它的联接使用方法一样了
*/
public void executeInsert(String s)
{
try{
conn = DriverManager.getConnection(sConnStr);
Statement statement = conn.createStatement();
statement.executeUpdate(s);
}catch(SQLException sqlexception){
System.err.println(”faq.executeUpdate:” + sqlexception.getMessage());
}
}
/**
* 取得应用程序运行的跟目录
*/
public String getFilePathRoot(){
String filepath=”";
filepath = this.getClass().getResource(”").getPath();
filepath = filepath.substring(0,filepath.indexOf(”/WEB-INF”));
filepath = filepath.substring(1,filepath.length());
return filepath;
}
}