天天看點

Javascript讀取ACCESS資料庫

 這些操作也許用不上,但也帖上來,網上也有很多相關例子,不多說帖出我自己改寫的一段,歡迎指正

說明:

在存html檔案的目錄下有一個存放資料庫的子目錄:webData,其中的資料庫名為scData.mdb

資料庫中有一個userlist的表,有userid和username兩個字段,并有一條userid='999',username='smallcol'的測試資料

js代碼:

檔案scEngine.js

//仿資料庫連接配接池類

function scDBPool(){

    try{

         this.con=new ActiveXObject("ADODB.Connection");

         this.con.Provider="Microsoft.Jet.OLEDB.4.0";

         this.rs=new ActiveXObject("ADODB.Recordset");

    }catch(e){

         this.con=null;

         this.rs=null;

    }

    this.filePath=null;

    this.dbPath=null;

};

//設定資料庫檔案相對(定位檔案)路徑和資料庫名

scDBPool.prototype.setDB=function(dbPath){

    this.dbPath=dbPath;

};

//設定資料庫定位檔案,這一步可以進連接配接類中,這裡寫是友善使用任何名字的資料庫

scDBPool.prototype.setDBPathPosition=function(urlFile){

    var filePath=location.href.substring(0, location.href.indexOf(urlFile));

    this.dbPath=(this.dbPath==null||this.dbPath=="") ? "/webData/scData.mdb" : this.dbPath;

    var path=filePath+this.dbPath;

   //去除path前面的"files://"字元串

    this.filePath=path.substring(8);

};

//同資料庫建立連接配接

scDBPool.prototype.connect=function(){

    this.con.ConnectionString="Data Source="+this.filePath;

    this.con.open;

};

//執行資料庫語句傳回結果集

scDBPool.prototype.executeQuery=function(sql){

    this.rs.open(sql,this.con);

};

//執行資料庫語句不傳回結果集

scDBPool.prototype.execute=function(sql){

    this.con.execute(sql);

};

//關閉結果集

scDBPool.prototype.rsClose=function(){

    this.rs.close();

    this.rs=null;

};

//關閉資料連接配接

scDBPool.prototype.conClose=function(){

    this.con.close();

    this.con=null;

};

html檔案中調試應用,頁面aa.html為資料庫相對定位檔案

<script language="javascript">

var db=new scDBPool();

db.setDBPathPosition("aa.html");

db.connect();

var sql="select * from [userlist] where userid = '999'";

db.executeQuery(sql);

while(!db.rs.eof){

    var cnt = db.rs.Fields("username");

    document.write(cnt);

    db.rs.moveNext;

}

db.rsClose();

db.conClose();

</script>

以上為個人參考網上改寫,有錯誤的地方請指正,謝謝,本人正在不斷學習中