您的位置:首页 > 数据库

JS读取ACCESS数据库类,已封装

2015-12-04 14:54 387 查看
// JavaScript Document

/*

javascript操作ACCESS数据库类

程序名:jsaccess.js

适用:windows环境下,IE浏览器

by adengou 2015.11.20

*/

/*基本参数

rs.Fields.Count//表中字段数量

rs.Fields(i).name//第i个字段名称

rs.Fields(i).vale//第i个字段值

rs.recordcount//数据库记录总数

*/

(function(){

var _JSACCESS ={};

/// 建立数据库连接

_JSACCESS.conn=function(dbfFilePath){

try{

var conn = new ActiveXObject("ADODB.Connection");

var conStr ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+dbfFilePath+" ";

//var conStr ="DBQ="+dbfFilePath+";DRIVER={Microsoft Access Driver (*.mdb)};";

conn.open(conStr);//conn.Open(conStr);

return conn;

}catch(e){

alert(e.description);

return null;

}

}

///定义RS

_JSACCESS.rs =function(){

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

rs.CursorType = 1;

rs.CursorLocation = 2;

rs.LockType = 3;//可读可写模式

return rs;

}

//关闭数据库

_JSACCESS.closeDB =function(conn,rs){

rs.close();

rs = null;

conn.close();

conn = null;

}

//查询记录

_JSACCESS.query = function(dbfFilePath,sql){

var conn = this.conn(dbfFilePath);

if(conn==null){return "";}

var rs = this.rs();

//

rs.open(sql, conn);

var str ="";

var arrData =new Array();

while(!rs.EOF&&!rs.BOF){

str ="{";

for(var i=0;i<rs.Fields.Count;i++){

str +="\""+rs.Fields(i).name+"\""+":"+"\""+rs.Fields(i).value+"\"";

str +=",";

}

str +="}";

arrData.push(str);

rs.moveNext;

}

this.closeDB(conn,rs);//关闭数据库

return arrData;//返回JSSON 数据 接收用 var receiveData =eval("("+arrData[0]+")");来解析

}

//获取数据库记录总数

_JSACCESS.getDataCount = function(dbfFilePath,sql){

var conn = this.conn(dbfFilePath);

if(conn==null){return 0;}

var rs = this.rs();

rs.open(sql, conn);

var count =rs.recordcount;

this.closeDB(conn,rs);

return count;

}

///增加记

_JSACCESS.insert =function(dbfFilePath,sql){

var conn =this.conn(dbfFilePath);

if(conn==null){ alert("数据库连接不成功!");return false;}

//

// sql="insert into addresslist(name,department,cellphone) values('name','department','13xxxxxxxxxx')";

try{

conn.execute(sql);

conn.close();

conn =null;

return true;

}catch(e){

alert("error_insert:"+e.message);

conn.close();

conn =null;

return false;

}

}

///修改记录

_JSACCESS.modify =function(dbfFilePath,sql){

var conn =this.conn(dbfFilePath);

if(conn==null){return false;}

// sql="update addresslist set name='name' where id=2";

try{

conn.execute(sql);

conn.close();

conn =null;

return true;

}catch(e){

alert("error_modify:"+e.message);

conn.close();

conn =null;

return false;

}

}

//

///删除记录

_JSACCESS.del =function(dbfFilePath,sql){

var conn =this.conn(dbfFilePath);

if(conn==null){return false;}

// sql="delete * from addresslist where id=2";

try{

conn.execute(sql);

conn.close();

conn =null;

return true;

}catch(e){

alert("error_del:"+e.message);

conn.close();

conn =null;

return false;

}

}

//

window["_JSACCESS"]=_JSACCESS;

})();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: