这几天费了挺大力气在网上查找javascript连接access数据库的方法,
经过整理总结,终于写出一段能够有效执行的代码。
但是这段代码在本地可以正常运行,一旦放到免费个人空间上就没法执
行了,主要原因就是操作权限不够,由于只支持静态页面的免费空间多数都
作了非常严格的限制,所以无论是用mdb的方式,还是读写纯文本文件的方式
都没办法通过,而由页面报出js错误。国外的一些免费空间,直接就禁止mdb
这样扩展名的文件上传。
虽然没希望在纯静态页面的免费空间上作自己的计数器或是留言版,但是
这段程序也许还是对一些朋友有用处,写出来供各位研究一下。
文件构成:
access数据库名为 mydata.mdb, 里面建了一个名为count的表,表由两个
字段组成: id和count,表里有一条数据: ('count','100')。
文本文件名为 count.txt,里面随便写入一个数字。
静态页面名为cnt.htm。
以上3个文件都放在同一目录下。
由于采用access数据库,而它采用非标准sql语法,所以要注意在表名
和字段名上需要加方括号: []
下面是页面里的代码:
其中getcountfromdb方法是对access数据库进行操作,getcountfromtxt
方法是对txt纯文本进行操作,这两个方法都在本地执行通过。
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> new document </title>
<meta name="generator" content="editplus">
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<script language="javascript">
<!--
function getcountfromdb() {
<html>
<head>
<title> new document </title>
<meta name="generator" content="editplus">
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<script language="javascript">
<!--
function getcountfromdb() {
//以当前页面文件为基础,找到文件所在的绝对路径。
var filepath = location.href.substring(0, location.href.indexof("cnt.htm"));
var path = filepath + "mydata.mdb";
var filepath = location.href.substring(0, location.href.indexof("cnt.htm"));
var path = filepath + "mydata.mdb";
//去掉字符串中最前面的"files://"这8个字符。
path = path.substring(8);
var updatecnt = 0;
path = path.substring(8);
var updatecnt = 0;
//生成查询和更新用的sql语句。
var sqlselcnt = "select count from [count] where id = 'count'";
var sqlupdcnt = "update [count] set [count] = '";
var sqlupdcnt = "update [count] set [count] = '";
//建立连接,并生成相关字符串。
var con = new activexobject("adodb.connection");
con.provider = "microsoft.jet.oledb.4.0";
con.connectionstring = "data source=" + path;
con.provider = "microsoft.jet.oledb.4.0";
con.connectionstring = "data source=" + path;
con.open;
var rs = new activexobject("adodb.recordset");
rs.open(sqlselcnt, con);
while (!rs.eof) {
var cnt = rs.fields("count");
document.write(cnt);
var rs = new activexobject("adodb.recordset");
rs.open(sqlselcnt, con);
while (!rs.eof) {
var cnt = rs.fields("count");
document.write(cnt);
//将取得结果加1后更新数据库。
updatecnt = cnt * 1 + 1;
rs.movenext;
}
rs.close();
rs = null;
updatecnt = cnt * 1 + 1;
rs.movenext;
}
rs.close();
rs = null;
sqlupdcnt = sqlupdcnt + updatecnt + "'";
con.execute(sqlupdcnt);
con.execute(sqlupdcnt);