找 AppendChunk 找到的

金山词霸PDF文档取词攻略,让你使用PDF更方便。

加密的PDF文档解密或取词:

  在一些情况下,不能词霸不能对PDF文档取词,多数是因为PDF文件经过了加密。

  表现特征为:文章的内容选择后不能复制到剪贴板上,通过‘文件—‘文档安全性'可以看到加密级别。

  1、对于没有口令的加密,使用以下办法:

  首先‘文档安全性'中的‘主口令'如果显示的是‘否',表示这是没有口令的加密。可以进行以下操作:运行acrobat reader,点击‘文件—文档安全性',点击‘更改设置'按钮,将其对话框中的

  ‘禁止内容复制或提取,并停用可访问性'前的勾去掉即可(这里指40位加密级别,如果是128位加密级别操作则相反),这样词霸就可以取词了。

  2、对于有口令的加密,只有借助‘advanced PDF password Recovery'这个软件了,如何使用不再此一一赘述.

  同样, ‘文档安全性'中的‘主口令'显示的应该是‘是',它同样也适用于没有口令加密的文档。

  注意:1、此软件对用户级密码可能还是无效。

  2、此软件是共享软件,如果没有注册,去掉保护后的文档只能看到前面10%的内容,后面的将全是空白页。

  特别提醒:

  1、注意先‘Acrobat reader'后‘金山词霸'的安装顺序,安装完词霸,最好再运行一下‘插件设置工具',选择其中的‘安装Acrobat插件'。

  2、以图片形式保存的PDF文档,例如:扫描制作的文件等目前暂时无法取词。

  最新的Acrobat Reader 6.0和Acrobat 6.0取词:

  Acrobat Reader 6.0取词:将金山词霸的安装目录下的Xdict32.api复制到Adobe Reader 6.0的安装目录/Adobe/Acrobat 6.0/Reader/plug_ins 文件夹下即可。

  Acrobat 6.0取词:将金山词霸的安装目录下的Xdict32.api复制到Adobe 6.0的安装目录/Adobe/Acrobat 6.0/Acrobat/plug_ins文件夹下即可 

- 作者: mulin 2004年12月30日, 星期四 12:20  回复(0) |  引用(0) 加入博采

文件上传及下载
文件上传

一.     在Form中一定要将encType设为"multipart/form-data":

二.     判断是否有文件上传了:

三.     判断上传文件MIMIE类型:
四.     保存上传的文件:

文件下载

一.     服务端通过Response输出相应的HTTP Response Headers信息,和要下载的文件的数据来把文件发送到客户端,HTTP Response Headers表现在html文件中是下面的形式:

文件上传
一.     在Form中一定要将encType设为"multipart/form-data":
<form id="WebForm3" method="post" encType="multipart/form-data" runat="server" >
二.     判断是否有文件上传了:
当用户没有选择任何要上传的文件,即HtmlInputFile控件中的文本框为空时点击了上传按钮后,在服务端得到的File1.PostedFile对象不是null,而是有对象的,所以不能用(File1.PostedFile == null)来判断是否上传了文件,用(File1.PostedFile.ContentLength != 0)来判断比较好
三.     判断上传文件MIMIE类型:
文件上传后可以用File1.PostedFile.ContentType来读取这个文件的MIMIE类型,这个MIMIE类型是系统通过上传文件的后缀名来获得的。
四.     保存上传的文件:
1.       文件可以通过File1.PostedFile.SaveAs(path) //path是服务器上的物理路径,来保存文件。

if(File1.PostedFile.ContentLength != 0)

{
       StringBuilder myStr = new StringBuilder();
       myStr.Append("文件名称:" + File1.PostedFile.FileName);
       myStr.Append("<br>");
       myStr.Append("文件类型:" + File1.PostedFile.ContentType);
       myStr.Append("<br>");
       myStr.Append("文件长度:" + File1.PostedFile.ContentLength.ToString());
       myStr.Append("<br>");
      
       string path = Server.MapPath("./");  //当前路径
       string fileName = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf('//')+1);
       path += fileName;
       if(File.Exists(path) == true)
       {
              Label1.Text = "服务器上已经有了你正在上传的文件:" + fileName;
              return;
       }
       File1.PostedFile.SaveAs(path);

       myStr.Append("保存完毕!");
       myStr.Append("<br>");
       Label1.Text = myStr.ToString();
}
else
{
       Label1.Text = "你没有选择要上载的文件或者上传的文件长度为0!";
}


2.       文件也可以通过二进制的读取后存放到数据库的二进制的字段中:
byte[] fileCont = new byte[File1.PostedFile.ContentLength];
File1.PostedFile.InputStream.Read(fileCont,0, File1.PostedFile.ContentLength);
然后将此字节数组fileCont赋给数据库的二进制字段的参数,写到数据库中。
文件下载
一.     服务端通过Response输出相应的HTTP Response Headers信息,和要下载的文件的数据来把文件发送到客户端,HTTP Response Headers表现在html文件中是下面的形式:
<meta http-equiv="Content-Type" content="text/htm ">
http-equiv表示是Headers的名称,content表示这个Headers的值
二.     首先,要输出文件的MIME类型:
Page.Response.AddHeader( "Content-Type", "MIME类型" ); 
三.     其次,要输出下载的文件的打开位置和文件名:
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName );
content-disposition 的 HTTP response header 允许指定文档表示的信息。使用这种 header ,你就可以将文档指定成单独打开(而不是在浏览器中打开),还可以根据用户的操作来显示。如果用户要保存文档,你还可以为该文档建议一个文件名。这个建议名称会出现在 Save As 对话框的"文件名"栏中。
打开位置:
attachment ―― 表示作为附件发送到客户端,客户端将单独打开此文件。
inline ―― 表示将在浏览器中打开这个文件。
文件名:
filename ―― 表示发送到客户端文件的文件名。
四.     准备发送到客户端的文件数据:
1.       先将不同类型来源的数据转成byte类型的数组,再通过Response.BinaryWrite方法发送到客户端:
1.1.      读取文件来获得byte数组:

string FileName;  //生成或获取要发送到客户端的文件名

string filePath = Server.MapPath("./") + FileName;  //假设文件在当前目录下
if(File.Exists(filePath) == false)
{
       //服务器上没有这个文件
       return;
}
FileStream myFile = File.OpenRead(filePath);  //读取文件进入FileStream
byte[] fileCont = new byte[myFile.Length];
myFile.Read(fileCont,0,(int)myFile.Length);   //将文件流中的内容转成byte数组


1.2.      在数据库的二进制字段中读取:

//从url获取图片的id

string ImageId = Request.QueryString["img"];
//构建查询语句
string sqlText = "SELECT img_data, img_contenttype FROM Image WHERE img_pk = " + ImageId;
SqlConnection connection = new SqlConnection( ConfigurationSettings.AppSettings["DSN"].ToString() );
SqlCommand command = new SqlCommand( sqlText, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if ( dr.Read())
{
       byte[] fileCont = (byte[]) dr["img_data"] ;
}
connection.Close();


1.3.      从internet上读取文件:

HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create( "http://www.via.com/aa.xls ");

HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
Stream readStream = myWebResponse.GetResponseStream();
                    
byte[] bytes = new byte[readStream.Length];
bytes = readStream.Read(bytes,0,readStream.Length);


通过上述三种方法获得的文件内容的byte数组就可以用来输出了:
Page.Response.BinaryWrite(fileCont);

Page.Response.End();

2.       直接读取文件输出:

- 作者: mulin 2004年11月29日, 星期一 00:15  回复(0) |  引用(0) 加入博采

·

您注册的搜狐闪电邮件为:kogm577@sohu.com 昵称为:kogm577_NEW
您同时获得了 kogm577@sohu.com 作为您的SOHU通行证。您可以通过使用此通行证,方便的使用SOHU提供的各项产品

 

另外:http://ftp.ik8.com/Reg2.asp

请记住您的通行证号码:

您的通行证号码:460032 您的社区昵称是:prettygulin
您的电子邮件地址:kogm577@sohu.com IK8网上之家生日:2004年11月18日

请记住您的通行证号码,并用该号码登陆
您的通行证号码是:460032
  • 通行证号码是标志您的唯一表示,如果您忘记了号码,您可以取回您的通行证号码
  • 您必须使用您的通行证号码登陆管理您的个人主页以及其他服务
  • 如果您忘记了您的通行证号码,可以从您的注册邮箱中查看您的通行证号码
  • 您可以通过EMAIL或者通行证号码两重方式来登陆您的管理
您的昵称是 prettygulin
您的电子邮件地址是 kogm577@sohu.com
IK8网上之家生日:2004年11月18日


- 作者: mulin 2004年11月18日, 星期四 12:22  回复(0) |  引用(0) 加入博采

JavaScript/Jscript核心语言对象扩充函数
JavaScript/Jscript 核心语言对象扩充函数
一、对象函数的扩充和代码
扩充函数的对象包括 Array、 String、 Date、 Number、 Boolean。
Array对象扩充函数
函数名
参数
说明
indexOf
_value
返回数组中值等于参数_value的元素索引位置,如果没有返回-1
lastIndexOf
_value
返回数组中值等于参数_value的元素反向索引位置,如果没有返回-1
contains
_value
返回数组中是否存在值等于参数_value的元素,true为存在,false不存在
copy
 拷贝数组到一个新数组中
insertAt
_value, i
插入参数值_value到参数i指定索引的位置上
insertBefore
_value, _invalue
插入参数值_value到数组中值等于参数_inValue的元素前
removeAt
i
删除索引位置为i的元素
remove
_value
删除值为_value的元素
String对象扩充函数
函数名
参数
说明
trim
 返回去掉前后空白字符的字符串
lTrim
 返回去掉左边的空白字符的字符串
rTrim
 返回去掉右边的空白字符的字符串
lTrimZero
 返回去掉左边的"0"字符的字符串
left
_leftNum
返回左边_leftNum个字符
right
_rightNum
返回右边_rightNum个字符
hasAlpha
 判断字符串是否有Alpha字符(@#$等非数字字母字符)
isAlpha
 判断字符串是否完全是Alpha字符
isLetter
 判断字符串是否完全是字母字符
isFigure
 判断字符串是否完全是数字字符
isDomainName
 判断字符串是否是一个合法的域名字符串
isEmail
 判断字符串是否是一个电子邮件地址
isHex
 判断字符串是否是十六进制字符
isGuid
 判断字符串是否是Guid值
isInteger
_bitType
判断字符串是否可为指定_bitType类型的整型数("64bit"||"32bit"||"16bit")
isInt8
 判断字符串是否可为int8的整型数
isInt16
 判断字符串是否可为int16的整型数
isInt32
 判断字符串是否可为int32的整型数
isInt64
 判断字符串是否可为int64的整型数
toDate
 将字符串转换成时间类型数值,能够转成合法Date的字符形如:yyyy-mm-dd or yyyy/mm/dd
toNumber
 将字符串转换成为数字类型数值
Date对象扩充函数
函数名
参数
说明
getQuarter
 返回时间的季度值
dateAdd
_timeInterval, _number
返回间隔_number量的时间,_timerInterval为间隔类型,分别有年(yyyy),月(mm),日(dd),时(h),分(m),秒(s),星期(ww)
formatDateTime
_nameFormate
返回时间的格式化字符串,_nameFormate为格式类型,此函数可参考vbs同名函数
isNaN
 时间变量是否是合法的,true为非法变量,false为合法的。
Number对象扩充函数
函数名
参数
说明
abs
 返回值的绝对值
acos
 返回值以弧度为单位的反余弦
asin
 返回值以弧度为单位的反正弦
atan
 返回值以弧度为单位的反正切
atan2
_value
返回值与_value的商的反正切
ceil
 返回大于等于值的下一个整数
cos
 返回值的余弦
exp
 返回值的欧拉常量
floor
 返回小于值等于值的整数
log
 返回值以e为底的自然对数
round
 返回值四舍五入后的数
sin
 返回值以弧度为单位的正弦
sqrt
 返回值的平方根
isNaN
 判断是否是一个合法的数值
tan
 返回值以弧度为单位的正切
浏览器中上述对象扩充了两个消息提示函数 alert和 cofirm,可以直接使用对象引用函数来弹出消息框。

代码部分:
-----------------------------------------------------------------------------------------------------------------------
Array.prototype.indexOf = function(_value){

         for(var i=0;i

         return -1;
};
Array.prototype.lastIndexOf = function(_value){
         for(var i=this.length-1;i>=0;i--)if(this[i]==_value)return i;
         return -1;
};
Array.prototype.contains = function(_value){return this.indexOf(_value)!= -1;};
Array.prototype.copy = function(){return this.concat();};
Array.prototype.insertAt = function(_value,i){this.splice(i,0,_value);};
Array.prototype.insertBefore = function(_value,_inValue){
         var i=this.indexOf(_inValue);
         if(i== -1)this.push(_value);
         else this.splice(i,0,_value);
};
Array.prototype.removeAt = function(i){this.splice(i,1);};
Array.prototype.remove = function(_value){
         var i=this.indexOf(_value);
         if(i!= -1)this.splice(i,1);
};
String.prototype.trim = function(){return this.replace(/(^/s+)|/s+$/g,"");};
String.prototype.lTrim = function(){return this.replace(/(^/s+)/g,"")};
String.prototype.rTrim = function(){return this.replace(/(/s+$)/g,"")};
String.prototype.lTrimZero = function(){return this.replace(/(^0+)/g,"")};
String.prototype.left = function(_leftNum){return this.substr(0,_leftNum)};
String.prototype.right = function(_rightNum){return this.substr(this.length - _rightNum)};
String.prototype.hasAlpha = function(){
         var _checkAlpha = /[/./*/+/?/|/(/)/{/}/[/]/-~`!@#$%^&_=:;"'<>,.]/;
         return(_checkAlpha.test(this));
};
String.prototype.isAlpha = function(){
         var _checkAlpha = /[^/./*/+/?/|/(/)/{/}/[/]/-~`!@#$%^&_=:;"'<>,.]/;
         return(!_checkAlpha.test(this));
};
String.prototype.isLetter = function(){return(!(//W/.test(this)||//d/.test(this)));};
String.prototype.isFigure = function(){return(!//D/.test(this));};
String.prototype.isDomainName = function(){return(!/[^/w-_/.]|^/.|/.$/.test(this));};
String.prototype.isEmail = function(){
         var _emailList = this.split("@");
         if(_emailList.length != 2)return false;
         return((!/[^/w-_]/.test(_emailList[0]))&&_emailList[1].isDomainName());
};
String.prototype.isHex = function(){return(!/[^/dABCDEFabcdef]/.test(this));};
String.prototype.isGuid = function(){
         if(this.left(1)!="{"||this.right(1)!="}")return false;
         var _hexNumberList = this.replace(/(^/{)|(/}$)/g,"").split("-");
         if(_hexNumberList.length!=5)return false;
         if(_hexNumberList[0].length!=8||!_hexNumberList[0].isHex())return false;
         if(_hexNumberList[1].length!=4||!_hexNumberList[1].isHex())return false;
         if(_hexNumberList[2].length!=4||!_hexNumberList[2].isHex())return false;
         if(_hexNumberList[3].length!=4||!_hexNumberList[3].isHex())return false;
         if(_hexNumberList[4].length!=12||!_hexNumberList[4].isHex())return false;
         return true;
};
String.prototype.isInteger = function(_bitType){
         var _limitValue = [];
         _limitValue["Upper"] = [];
         _limitValue["Lower"] = [];
         _limitValue["Upper"]["64bit"] = "9223372036854775807";
         _limitValue["Upper"]["32bit"] = "2147483647";
         _limitValue["Upper"]["16bit"] = "32767";
         _limitValue["Lower"]["64bit"] = "9223372036854775808";
         _limitValue["Lower"]["32bit"] = "2147483648";
         _limitValue["Lower"]["16bit"] = "32768";
         var _plus = "Upper";
         var _theValue = new String(this);
         if(_theValue.indexOf("-")==0){
                   _theValue = _theValue.substr(1,_theValue.length-1);
                   _plus = "Lower";
         }      
         if(!_theValue.isFigure())return false;
         if(_limitValue[_plus][_bitType].length < _theValue.length)return false;
         if(_limitValue[_plus][_bitType].length == _theValue.length){
                   for(var i=0;i<_limitValue[_plus][_bitType].length;i++){
                            if(_theValue.charAt(i) < _limitValue[_plus][_bitType].charAt(i))return true;
                   }
                   if(_limitValue[_plus][_bitType] != _theValue)return false;
         }
         return true;
};
String.prototype.isInt8 = function(){
         var _theValue = this.toNumber();
         if(_theValue.isNaN())return false;
         if(_theValue < 0 || _theValue > 255)return false;
         if(_theValue.toString() != this)return false;
         return true;
};
String.prototype.isInt16 = function(){return this.isInteger("16bit");};
String.prototype.isInt32 = function(){return this.isInteger("32bit");};
String.prototype.isInt64 = function(){return this.isInteger("64bit");};
String.prototype.toDate = function(){
         var _dateStr = this.trim().split(//s/)[0];
         var _timeStr = (this.trim().split(//s/)[1]?this.trim().split(//s/)[1]:"1:1:1");
         var _dateSplitSymbol = /[///-,年]/;
         var _timeSplitSymbol = /[:,时]/;
         if(!_dateSplitSymbol.test(_dateStr))return new Date("x");
         var _SplitSymbol = _dateSplitSymbol.exec(_dateStr);
         var _dateList = [];
         if(_SplitSymbol == "年"){
                   if(!(_dateStr.indexOf("日") > _dateStr.indexOf("月") && _dateStr.indexOf("月") > _dateStr.indexOf("年") && _dateStr.indexOf("年")> 1))return new Date("x");
                   _dateList = _dateStr.split(/[年月日]/);
         }else _dateList = _dateStr.split(_SplitSymbol);
         if(_dateList.length < 2)return new Date("x");
         var _timeList = [1,1,1];
         if(_timeSplitSymbol.test(_timeStr)){
                   _SplitSymbol = _timeSplitSymbol.exec(_timeStr);
                   if(_SplitSymbol == "时"){
                            if(!(_timeStr.indexOf("秒") > _timeStr.indexOf("分") && _timeStr.indexOf("分") > _timeStr.indexOf("时") && _timeStr.indexOf("时")> 1))return new Date("x");
                            _timeList = _timeStr.split(/[时分秒]/);
                   }else _timeList = _timeStr.split(_SplitSymbol);
         }
         return new Date(_dateList[0],_dateList[1],_dateList[2],_timeList[0],_timeList[1],_timeList[2]);
};
String.prototype.toNumber = function(){return new Number(this)};
Date.prototype.getQuarter = function(){return ((this.getMonth()+1)/3).ceil();};
Date.prototype.dateAdd = function(_timeInterval,_number){
         switch(_timeInterval.toUpperCase()){
                   case "YYYY":
                            return new Date(this.getFullYear() + _number,this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds());
                            break;
                   case "MM":
                            return new Date(this.getFullYear(),this.getMonth() + _number,this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds());
                            break;
                   case "DD":
                            return new Date(this.getFullYear(),this.getMonth(),this.getDate() + _number,this.getHours(),this.getMinutes(),this.getSeconds());
                            break;
                   case "H":
                            return new Date(this.getFullYear(),this.getMonth(),this.getDate(),this.getHours() + _number,this.getMinutes(),this.getSeconds());
                            break;
                   case "M":
                            return new Date(this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes() + _number,this.getSeconds());
                            break;
                   case "S":
                            return new Date(this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds() + _number);
                            break;
                   case "WW":
                            return new Date(this.getFullYear(),this.getMonth(),this.getDate() + _number*7,this.getHours(),this.getMinutes(),this.getSeconds());
                            break;
                   default:return this;
         }
};
Date.prototype.formatDateTime = function(_nameFormate){
         switch(_nameFormate){
                   case 0:
                            return this.getFullYear().toString().right(2) + "/" + (this.getMonth() + 1).toString() + "/" + this.getDate().toString() + " " + this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString();
                            break;
                   case 1:
                            return this.getFullYear().toString() + "年" + (this.getMonth() + 1).toString() + "月" + this.getDate().toString() + "日";
                            break;
                   case 2:
                            return this.getFullYear().toString().right(2) + "/" + (this.getMonth() + 1).toString() + "/" + this.getDate().toString();
                            break;
                   case 3:
                            return this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString();
                            break;
                   case 4:
                            return this.getHours().toString() + ":" + this.getMinutes().toString();
                            break;
                   default:
                            return this.getFullYear().toString().right(2) + "/" + (this.getMonth() + 1).toString() + "/" + this.getDate().toString() + " " + this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString();
         }
};
Date.prototype.isNaN = function(){return isNaN(this);};
Number.prototype.abs = function(){return Math.abs(this)};
Number.prototype.acos = function(){return Math.acos(this)};
Number.prototype.asin = function(){return Math.asin(this)};
Number.prototype.atan = function(){return Math.atan(this)};
Number.prototype.atan2 = function(){return Math.atan2(this)};
Number.prototype.ceil = function(){return Math.ceil(this)};
Number.prototype.cos = function(){return Math.cos(this)};
Number.prototype.exp = function(){return Math.exp(this)};
Number.prototype.floor = function(){return Math.floor(this)};
Number.prototype.log = function(){return Math.log(this)};
Number.prototype.round = function(){return Math.round(this)};
Number.prototype.sin = function(){return Math.sin(this)};
Number.prototype.sqrt = function(){return Math.sqrt(this)};
Number.prototype.isNaN = function(){return isNaN(this)};
Number.prototype.tan = function(){return Math.tan(this)};
if(window){
         Array.prototype.alert = function(){window.alert(this);}
         Array.prototype.confirm = function(){return window.confirm(this);}
         String.prototype.alert = function(){window.alert(this)};
         String.prototype.confirm = function(){return window.confirm(this)};
         Date.prototype.alert = function(){window.alert(this.toLocaleDateString());};
         Date.prototype.confirm = function(){return window.confirm(this.toLocaleDateString());};
         Number.prototype.alert = function(){window.alert(this)};
         Number.prototype.confirm = function(){return window.confirm(this)};
         Boolean.prototype.alert = function(){window.alert(this);};
         Boolean.prototype.confirm = function(){return window.confirm(this);};
}
-----------------------------------------------------------------------------------------------------------------------
二、关于prototype 属性
JavaScript1.1中,几个基本对象String、RegExp、Array、Date、Number、Boolean、Function增加了一个原型(prototype)属性,该属性容许程序员向已有对象原型添加新的属性和函数。其用法如下:
function obj(){
         this.id = "";
}
obj.prototype.set_id = function(_value){
         this.id = _value;
}
var obj1 = new obj();
obj1.set_id("test");
通过prototype属性给obj类(事实上不是类,而是一个函数,这里只是为了方便表述)创建了一个函数(给set_id赋值为一个函数)。
prototype对于自定义的伪类意义不是很大,因为自定义的伪类也完全可以在构造函数中创建。
但是它对于已有的JavaScript对象类型的函数扩充有着比较重要的意义,通过prototype,可以给JS基本对象扩充新的函数。例如在js中没有类似于vbs中的trim函数,倘若单独把trim函数以及其他有用的函数写成一个独立的函数库,又失去了js脚本的那种语言简洁的特点。最理想的情况是将它扩充到已有的对象原型中去。
看看一些有趣的例子:
("  1234  ").trim().alert();  //弹出一个对话框提示为1234
if(text1.value.toDate().isNaN())alert("date input error!");  //在一个文本框中输入时间,格式不正确提示错误!

扩充的函数中比较有实用的是String的函数,trim,left,right,isXXX等函数在表单的验证当中是比较常用的。

- 作者: mulin 2004年10月27日, 星期三 17:15  回复(0) |  引用(0) 加入博采

用JavaScript制作站内搜索
用javascript做的站内搜索不仅编程实现、维护起来很简单,而且它能在客户端浏览器直接执行,无须服务器的支持,也可以省去申请有脚本执行权限空间的麻烦。所以,只要你愿意动手,有个人主页就能有自己的站内搜索。下面让我们共同来做一个基于javascript的站内搜索的脚本,可不要小看它,做完了你就知道它的好处了。
  首先,你要编写一个搜索表单,将用户要搜索的数据提交给javascript函数。最简单的代码如下,因为是最简单的HTML代码,所以就不作解释了:
  
  
    或者(or)  并且(and)  不包含(no)  
  
  
  其次,要对你的站点的数据初始化。这是搜索时要用到的数据库,站点更新只要更改这些数据就行了。对于这个数据库,建议单独存为一个文件,在这里我们先存为相同路径下的″db.js″
  /* 站点数据库db.js开始 */
  function initArray(){ /* 定义数组初始化函数 */
  this.length=initArray.arguments.length;
  for(var i=0;i  }
  /* 定义待搜索的页面的标题,没有先后顺序,应将待搜索的页面都列出 */
  var titles=new initArray(′页面标题1′,′页面标题2′,......);
  /* 这些页面的详细说明,位置应该与它们的标题一致 */
  var descriptions=new initArray(′详细说明1′,′详细说明2′,......);
  /* 待搜索页面的地址,建议使用在你站点上的相对地址,位置也应与标题、说明相一致 */
  var URLs=new initArray(′url1′,′url2′,......);
  /* 站点数据库db.js结束 */
  第三步,初始化用户输入的搜索字符串,并将它传递给搜索函数,列出结果。

  function goSearch(){
  var searchStr=document.search.searchStr.value; /* 取得表单中的用户输入的搜索字符 */
  var string1=searchStr.toLowerCase(); /* 转换为小写,避免大小写敏感 */
  var length1=string1.length;
  var string2=′′;
  for(var i=0;i<3;i++){ /* 取得搜索的字符串的各个关键字的逻辑关系 */
  if(document.search.select.options[i].selected) logic=i;}
  if(length1!=0&&string1!=′ ′&&string1!=′ ′){ /* 滤掉″空″关键字 */
  for(i=0;i  else string2+=string1.charAt(i);}
  var search=string2.split(′+′); /* 将转换过的搜索字符串以″+″为分割符分割为一个字符串数组 */
  uptodataSearch(search);
  outWin=window.open(′′,′′,′′); doc=outWin.document.
  if(hitCount!=0){ /* 如果检索到符合要求的页面 */
  doc.write(′

检索结果:共有′+hitCount+′个页面符合字符串:″′+string2+′″:

  • ′);
      for(i=0;i  doc.write(′
  • ′);
      hrefmaker(titles[index[i]],URLs[index[i]],descriptions[index[i]]); /* 把检索到的数据一一列出,这里调用到的链接生成函数hrefmaker()在下面给出 */
      doc.write(′′);}
      doc.write(′
′);
  }
  else doc.write(′

很抱歉,本站没有关于″′+string2+′″的内容!

′);
  }
  else alert(′请输入要搜索的关键字!′);
  }
  第四,编写搜索函数。限于篇幅,给出的函数只有"不包含"的功能(就是输入的多个关键字必须全部满足要求才算符合搜索结果),要实现″或者″、″并且″功能请访问以下链接:http://ctsight.topcool.net/document./pt_nr2000050902.html。
  var hitCount=0; /* 全局变量hitCount,用于记录符合搜索要求的页数 */
  var index=new Array(); /* 全局变量数组,用于保存符合搜索要求的的页面在″数据库″db.js中的位置 */
  function uptodataSearch(searchStr){ /* 以经过处理的用户输入的搜索字符串为参数的搜索函数 */
  var tmpCount1=0,tmpCount2=0;
  var tmpStr=′′,des=′′;
  var length1=searchStr.length,length2=titles.length;
  for(var i=0;i  tmpStr=titles[i]+descriptions[i]; /* 将本次循环的站点数据的标题与详细内容合并,作为本次检索的范围*/
  des=tmpStr.toLowerCase(); /* 同样将它转化为小写 */
  tmpCount1=tmpCount2;
  if(logic==2){ /* 如果逻辑关系是″不包括(not,!)″ */
  if(des.indexOf(searchStr[0])!=-1){ //首先必须满足第一个关键字要求
  for(j=1;j  首先,你要编写一个搜索表单,将用户要搜索的数据提交给javascript函数。最简单的代码如下,因为是最简单的HTML代码,所以就不作解释了:
  
  
    或者(or)  并且(and)  不包含(no)  
  
  
  其次,要对你的站点的数据初始化。这是搜索时要用到的数据库,站点更新只要更改这些数据就行了。对于这个数据库,建议单独存为一个文件,在这里我们先存为相同路径下的″db.js″
  /* 站点数据库db.js开始 */
  function initArray(){ /* 定义数组初始化函数 */
  this.length=initArray.arguments.length;
  for(var i=0;i  }
  /* 定义待搜索的页面的标题,没有先后顺序,应将待搜索的页面都列出 */
  var titles=new initArray(′页面标题1′,′页面标题2′,......);
  /* 这些页面的详细说明,位置应该与它们的标题一致 */
  var descriptions=new initArray(′详细说明1′,′详细说明2′,......);
  /* 待搜索页面的地址,建议使用在你站点上的相对地址,位置也应与标题、说明相一致 */
  var URLs=new initArray(′url1′,′url2′,......);
  /* 站点数据库db.js结束 */
  第三步,初始化用户输入的搜索字符串,并将它传递给搜索函数,列出结果。
  function goSearch(){
  var searchStr=document.search.searchStr.value; /* 取得表单中的用户输入的搜索字符 */
  var string1=searchStr.toLowerCase(); /* 转换为小写,避免大小写敏感 */
  var length1=string1.length;
  var string2=′′;
  for(var i=0;i<3;i++){ /* 取得搜索的字符串的各个关键字的逻辑关系 */
  if(document.search.select.options[i].selected) logic=i;}
  if(length1!=0&&string1!=′ ′&&string1!=′ ′){ /* 滤掉″空″关键字 */
  for(i=0;i  else string2+=string1.charAt(i);}
  var search=string2.split(′+′); /* 将转换过的搜索字符串以″+″为分割符分割为一个字符串数组 */
  uptodataSearch(search);
  outWin=window.open(′′,′′,′′); doc=outWin.document.
  if(hitCount!=0){ /* 如果检索到符合要求的页面 */
  doc.write(′

检索结果:共有′+hitCount+′个页面符合字符串:″′+string2+′″:

  • ′);
      for(i=0;i  doc.write(′
  • ′);
      hrefmaker(titles[index[i]],URLs[index[i]],descriptions[index[i]]); /* 把检索到的数据一一列出,这里调用到的链接生成函数hrefmaker()在下面给出 */
      doc.write(′′);}
      doc.write(′
′);
  }
  else doc.write(′

很抱歉,本站没有关于″′+string2+′″的内容!

′);
  }
  else alert(′请输入要搜索的关键字!′);
  }
  第四,编写搜索函数。限于篇幅,给出的函数只有"不包含"的功能(就是输入的多个关键字必须全部满足要求才算符合搜索结果),要实现″或者″、″并且″功能请访问以下链接:http://ctsight.topcool.net/document./pt_nr2000050902.html。
  var hitCount=0; /* 全局变量hitCount,用于记录符合搜索要求的页数 */
  var index=new Array(); /* 全局变量数组,用于保存符合搜索要求的的页面在″数据库″db.js中的位置 */
  function uptodataSearch(searchStr){ /* 以经过处理的用户输入的搜索字符串为参数的搜索函数 */
  var tmpCount1=0,tmpCount2=0;
  var tmpStr=′′,des=′′;
  var length1=searchStr.length,length2=titles.length;
  for(var i=0;i  tmpStr=titles[i]+descriptions[i]; /* 将本次循环的站点数据的标题与详细内容合并,作为本次检索的范围*/
  des=tmpStr.toLowerCase(); /* 同样将它转化为小写 */
  tmpCount1=tmpCount2;
  if(logic==2){ /* 如果逻辑关系是″不包括(not,!)″ */
  if(des.indexOf(searchStr[0])!=-1){ //首先必须满足第一个关键字要求
  for(j=1;j  if(des.indexOf(searchStr[j])==-1) tmpCount2++;}
  if(tmpCount1==tmpCount2-length1+1){ /* 只有满足第一个关键字要求但不满足其它任何一个关键字的才算符合检索要求 */
  index[hitCount]=i; hitCount++;} } } } }
  第五,编写搜索页面。
  OK,基于javascript的站内搜索完工了。试一下,感觉如何?如要与我交流,请E-mail:contion@21cn.com。索其它关键字
  if(des.indexOf(searchStr[j])==-1) tmpCount2++;}
  if(tmpCount1==tmpCount2-length1+1){ /* 只有满足第一个关键字要求但不满足其它任何一个关键字的才算符合检索要求 */
  index[hitCount]=i; hitCount++;} } } } }
  第五,编写搜索页面。
  

- 作者: mulin 2004年10月14日, 星期四 22:14  回复(0) |  引用(0) 加入博采

点击下载任何格式的文件
Web开发人员都有过这样的疑问,如何让一个文件,尤其是一个已知类型的文件,发送到客户端,直接提示让浏览者下载,而不是用与它相关联的程序打开。以前我们最常用的办法就是把这样的文件加到链接上,这样可以让浏览者通过点击鼠标右键的目标另存为来下载所链接的文件。但是,这样有两个不足的地方:  
           一是:如果浏览器能够识别已下载文件的扩展名,则浏览器就会激活该扩展名所关联的程序来打开所下载的文件。比如:在Windows平台上,如果用户点击的链接链接的是一个".doc"文件的话,那么,浏览器就会启动Microsoft  Word应用程序来打开它。  
           二是:如果采用链接的办法的话,任何能看到该链接的人都可以下载该文件,你虽然也可以对所下载的文件进行权限设置,但那样做也不是很方便的。有时候我们需要更为灵活和富有弹性的方式,下面的程序能够很方便地克服以上两方面的不足。  
           这种办法是可靠的,但你必须记住:没有授权的用户不能够通过在浏览器地址栏里输入文件的URL来取得该文件的下载权。所以,要下载的文件应该放到虚拟目录之外的一个目录里,比如:如果你的虚拟目录是C:/Mengxianhui/Tomcat4/Website/MyApp的话,那么,存放在该目录和该目录下的任何子目录下所有文件对因特网上的任何用户都是可见的。要直接下载一个文件,我们需要做两件事,第一件事是:设定响应的内容类为"application/octet-stream",大小写无关。第二件事是:设置HTTP的响应头名字为:Content-Disposition,设定值为:attachment;  filename  =  theFileName。这里的theFileName就是出现在文件下载对话框里的默认文件名,通常和所下载的文件名字相同,但也可以不同。下面,我们就平常最常用的JSP和ASP页面来举一个实际应用的例子。  
             

             TestFileDownload.JSP页面的例子:  
               
               
             
           值得注意的是:在你要下载的文件内容里,除了文件的内容之外,不应该再附加有其它任何的字符,包括空格和回车换行符。我们有时在编写代码的时候,为了使代码清晰可读,往往会添加一些空格、制表符或者回车换行符,这样虽然看起来比较清晰,但有时可能会得不到正确的结果。比如:  
                          class="com.Mengxianhui.DownloadBean"  />  
           应该写成这样:  
                       class="com.Mengxianhui.DownloadBean"  />  
             
           TestFileDownload.ASP页面的例子:  
             
           在ASP里,没有提供从文件读取文件流信息的方法,因此,为了得到文件的流信息,我们必须借助其他的工具,最简单的就是编写一个VB或C的DLL组件,让组件返回文件的流信息。下面是一个用VB编写的DLL的例子,工程名字为MengXHFileDownLoad,类模块的名字为BinReadFromFile,类方法readBinFromFile如下:  
                         
           Function  readBinFromFile(ByVal  bfilename  As  String)  As  Variant  
                   Dim  fl  As  Long  
                   Dim  FileNum  As  Long  
                   Dim  binbyte()  As  Byte  
                   Dim  binfilestr  As  String  
                     
                   On  Error  GoTo  errHandler                      
                   FileNum  =  FreeFile                      
                   Open  bfilename  For  Binary  As  #FileNum                      
                   fl  =  FileLen(bfilename)  
                   ReDim  binbyte(fl)                      
                   Get  #FileNum,  ,  binbyte                      
                   Close  #FileNum                      
                   readBinFromFile  =  binbyte  
                   Exit  Function  
                                         
           errHandler:  
                   Exit  Function  
           End  Function  
             
           把上面的代码编译成MengXHFileDownLoad.DLL,然后注册即可使用。下面以直接下载一个When  A  Man  Loves  A  Woman.mp3的MP3文件为例子,我们要编写的ASP脚本代码如下:  
             
                         
                         
             
           当我们运行上面的TestFileDownload.ASP文件时,浏览器会弹出一个文件下载的对话框,提示我们下载,而不是用默认的MP3播放器打开。  
           这种方法也可以把我们的ASP页面生成的HTML源代码保存成一个文件,下面的代码会提示你把ASP执行的结果保存成Test.htm文件。具体的方法是:  
                         
             
           当我们的文件数目很少时,也可以直接在服务器端进行设置,让这些文件直接下载。具体做法是:在Internet服务管理器里,选"属性"项,然后选"HTTP  Headers"标签页进行设置即可!!

- 作者: mulin 2004年10月10日, 星期日 03:53  回复(0) |  引用(0) 加入博采

ASP初学者常犯的几个错误
 

1.记录集关闭之前再次打开:

2,用SQL关键字做表名或字段名

3,用锁定方式去进行update

4,在查询语句中采用的对比字段值与字段类型不符
5,未检查变量值而出错

6,未检查变量值类型而出错

7,由于数据库文件所在目录的NTFS权限而引起的'不能更新。数据库或对象为只读"错误。


------------------------------------
sql="select * from test"
rs.open sql,conn,1,1
if not rs.eof then
dim myName
myName=rs("name")
end if
sql="select * from myBook"
rs.open sql,conn,1,1
-------------------------------------
解决:在第二次rs.open之前先关闭 rs.close

set rs1=server.createobject
rs1.open sql,conn,1,1

2,用SQL关键字做表名或字段名
-------------------------------------
sql="select * from user"
rs.open sql,conn,1,1
-------------------------------------
user为sql关键字
解决:改为
sql="select * from [user]"


3,用锁定方式去进行update
-------------------------------------
sql="select * from [user]"
rs.open sql,conn,1,1
rs.addnew

rs("userName")="aa"
rs.update
-------------------------------------
当前记录集的打开方式为只读
解决:
改为
rs.open sql,conn,1,3

4,在查询语句中采用的对比字段值与字段类型不符
-----------------------------------------
sql="select * from [user] where id='" & myID & "'"
rs.open sql,conn,1,1
-----------------------------------------
假设表中设计ID为数字型,那么些时出错。
解决:
sql="select * from [user] where id=" & myID

5,未检查变量值而出错
-----------------------------------------
sql="select * from [user] where id=" & myID
rs.open sql,conn,1,1
-----------------------------------------
假设myID变量此时值为null,那么sql将成为
sql="select * from [user] where id="
解决:
在前面加上
if isnull(myID) then 出错提示

6,未检查变量值类型而出错
-----------------------------------------
sql="select * from [user] where id=" & myID
rs.open sql,conn,1,1
-----------------------------------------
假设id为数字型,myID变量此时值不为null,但为字符,比如myID此时为"aa"
那么sql将成为
sql="select * from [user] where id=aa"
解决:
在前面加上
if isnumeric(myID)=false then 出错提示

这也可以有效防止 sql injection 漏洞攻击。

7,由于数据库文件所在目录的NTFS权限而引起的'不能更新。数据库或对象为只读"错误。
说明:
WIN2K系统延续了WINNT系统的NTFS权限。
对于系统中的文夹都有默认的安全设置。
而通过HTTP对WWW访问时的系统默认用户是 iusr_计算机名 用户 ,它属于guest组。
当通过HTTP访问时,可以ASP或JSP,也或是PHP或.NET程序对数据进行修改操作:
比如:
当打开某一个文章时,程序设定,文章的阅读次数=原阅读次数+1
执行
conn.execute("update arts set clicks=clicks+1 where id=n")
语句时,如果 iusr_计算机名 用户没有对数据库的写权限时,就会出错.
解决方法:
找到数据库所在目录
右键》属性》安全选项卡》设置 iusr_计算机名 用户的写权限(当然,也可以是everyone)

- 作者: mulin 2004年10月10日, 星期日 02:16  回复(0) |  引用(0) 加入博采

Scripting.Dictionary对象

许多Microsoft的编程语言,如Visual Basic、VBScript和Jscript,都提供集合(collection)。可以把集合想象为数组,可以使用其中内建的函数完成存储和操纵数据等基本任务。无须担心数据是在哪些行列,而是使用唯一的键进行访问。
    VBScript和Jscript都提供类似的对象,通称Scripting.Dictionary对象或Dictionary对象。它类似于二维数组,把键和相关条目的数据存放在一起。然而真正的面向对象的方法,不应直接访问数据条目,必须使用Dictionary对象支持的方法和属性来实现。
    本章提供了一些示例页面,允许试验脚本运行期对象的方法和属性。



5.3.1 创建和使用Dictionary对象
    创建一个Dictionary对象的示例如下:
    ‘In VBScript:
    Dim objMyData
    Set objMyData = Server.CreateObject("Scripting.Dictionary")

    //In Jscript:
    var objMyData = Server.CreateObject(‘Scripting.Dictionary');

   
   
    Dictionary对象还可用于客户端的IE中。
1.    Dictionary对象的成员概要
表5-2和表5-3列出了Dictionary对象的属性和方法及相应的说明。
当增加一个键/条目对时,如果该键已存在;或者删除一个键/条目对时,该关键字/条目对不存在,或改变已包含数据的Dictionary对象的CompareMode,都将产生错误。
表5-2  Dictionary对象的属性和说明
属 性                                     说 明
CompareMode    (仅用于VBScript)设定或返回键的字符串比较模式
Count                   只读。返回Dictionary里的键/条目对的数量
Item(key)              设定或返回指定的键的条目值
Key(key)              设定键值
表5-3  Dictionary对象的方法和说明
方 法                               说 明
Add(key,item)              增加键/条目对到Dictionary
Exists(key)                   如果指定的键存在,返回True,否则返回False
Items()                         返回一个包含Dictionary对象中所有条目的数组
Keys()                         返回一个包含Dictionary对象中所有键的数组
Remove(key)               删除一个指定的键/条目对
RemoveAll()                删除全部键/条目对
2.    对Dictionary中增加和删除条目
一旦得到一个新的(空的)Dictionary,可以对其添加条目,从中获取条目以及删除条目:
‘ In VBScript:
objMyData.Add "MyKey", "MyItem"            ‘Add Value MyItem with key MyKey
objMyData.Add "YourKey", "YourItem"        ‘Add value YourItem with key YourKey
blnIsThere = objMyData.Exists("MyKey")        ‘Returns True because the item exists
strItem = objMyData.Item("YourKey")            ‘Retrieve value of YourKey
strItem = objMyData.Remove("MyKey")        ‘Retrieve and remove YourKey
objMyData.RemoveAll                        ‘Remove all the items
在JScript中,等价的代码为:
// In JScript;
objMyData.Add (‘MyKey', ‘MyItem');            //Add Value MyItem with key MyKey
objMyData.Add (‘YourKey', ‘YourItem');        //Add value YourItem with key YourKey
var blnIsThere = objMyData.Exists(‘MyKey');    //Returns True because the item exists
var strItem = objMyData.Item(‘YourKey');        //Retrieve value of YourKey
var strItem = objMyData.Remove(‘MyKey');    //Retrieve and remove YourKey
objMyData.RemoveAll();                    //Remove all the items
3.    修改键或条目的值
可以通过修改键的值,或通过修改与特定的键关联的条目的数据,来改变存储在Dictionary内的数据。下面的代码改变键为MyKey的条目中的数据。
ObjMyData.Item("MyKey") = "NewValue"        ‘ In VBScript
ObjMyData.Item(‘MyKey') = ‘NewValue';        // In JScript
如果指定的键在Dictionary未找到,将在Dictionary中创建一个以MyKey为键,以New Value为其条目值的新的键/条目对。有意思的是,如果使用一个不存在的键来检索条目,不仅得到一个空的字符串(这是可以想到的),而且还在Dictionary里添加一个新的键/条目对,键即是指定的键,但条目的数据为空。
可以使用Key属性仅改变键的值而不改变与之对应的条目的数据。将一个已存在的键MyKey改变为MyNewKey,可以用:
objMyData.Key("MyKey") = "MyNewValue"        ‘ In VBScript
objMyData.Item(‘MyKey') = ‘MyNewValue';        // In JScript
如果指定的键未找到,则产生运行期错误。
4.    设置比较模式
Dictionary的CompareMode属性仅适用于VBScript,不能在JScript中使用。当比较字符串键时,允许指定比较的方式。两个允许的值为BinaryCompare(0)和TextCompare(1)。BinaryCompare(0)为二进制数对照(即区分大小写);TextCompare(1)为文本对照(即不区分大小写)。
5.    遍历Dictionary
研究Dictionary时,有两个方法和一个属性需要特别注意,它们允许我们遍历存储在Dictionary里的所有键/条目对。Items方法用一个一维数组的形式返回Dictionary里所有的条目数据,而keys方法用一个一维数组返回所有已存在的键值。可以使用Count属性得到键或条目的数量。
例如,可以使用下列代码得到名称为objMyData的Dictionary中所有的键和条目值。注意,虽然Count属性保存了在Dictionary里的键/条目数量,但VBScript和JScript的数组总是从下标0开始的。因此,数组下标应从0到Count-1。
‘In VBScript:
arrKeys = objMyData.Keys                    ‘Get all the keys into an array
arrItems = objMyData.Items                    ‘Get all the items into an array

For intLoop = 0 To objMyData.Count -1        ‘Iterate through the array
    StrThisKey = arrKeys(intLoop)            ‘This is the key value
    StrThisItem = arrItems(intLoop)            ‘This is the item (data) value
Next

// In JScript
// Get VB-style arrays using the Keys() and Items() methods
var arrKeys = new VBArray(objMyData.Keys()).toArray();
var arrItems = new VBArray(objMyData.Items()).toArray();

for (intLoop = 0; intLoop < objMyData.Count; intLoop++) {
    // Iterate through the arrays
    strThisKey = arrKeys[intLoop];            // This is the key value
    strThisItem = arrItems[intLoop];            // This is the item (data) value
}
在VBScript里也可以使用For Each ... Next语句完成同样的功能:
‘ Iterate the dictionary as a collection in VBScript
For Each objItem in arrItems
    Response.Write objItem & " = " & arrItems(objItem) & "
"
Next
5.3.2 Dictionary对象示例
       本书提供了一系列示例文件可用来试验脚本运行时间库的各种属性。
       本章代码的缺省页面提供了一系列可使用的VBScript示例链接。有些示例对JScript同样有效。这些示例存放在Chapter05目录下相应的子目录里,显示的界面如图5-2所示:
        要查看Dictionary对象的运行,在菜单页面点击第一个链接,打开名叫show_dictionary.asp的页面。这个页面显示了我们提供的Dictionary对象的内容,允许试验其属性和方法。屏幕如图5-3所示:

1.  Dictionary的global.asa文件
随Dictionary对象示例页面提供的文件之一是global.asa。它创建并预先填充了一个会话层作用域的Dictionary对象,因此其内容在页面请求之间不会丢失。一般说来(考虑到可扩展性),这不是一个理想的做法。在这个例子里,可以看到Dictionary的属性和方法的效果。
如果在自己的服务器上下载并安装示例,必须创建一个基于此global.asa文件的虚拟应用程序。或者将其内容添加到缺省站点的根文件夹中的global.asa文件里。在第3章讲述了如何用向导创建虚拟应用程序。然而对于本示例,创建一个虚拟应用程序最简单的方法是在Chapter05示例文件夹内右击dictionary子文件夹,在Properties对话框的Home Directory选项卡里,点击Create按钮,如图5-4所示:

在这个global.asa文件里,代码使用


2.  Dictionary示例页面
在"Scripting.Dictionary Object"主页面里,首要的任务是得到一个会话层作用域的Dictionary对象实例的引用。注意,这个引用是一个对象变量,因此必须在VBScript里使用Set关键字。
然后,检查一下是否得到了一个对象(这是个好习惯),如果没有正确地建立包含global.asa文件的虚拟应用程序,检查一下问题出在哪里。你将看到我们自己的消息代替了ASP的错误消息(但是注意,对于这一操作必须关闭缺省的错误处理)。


 

Iterating the Dictionary with Arrays

...
... Other code and controls go here ...
...
  
显示在页面上的Dictionary内容列表是使用Dictionary对象的Key和Items方法创建的两个数组,可使用前面的代码遍历它们。
3.  Dictionary页面控件
在Dictionary的内容列表下是一系列的HTML控件,可用于设定Dictionary对象的某些属性和执行各种方法。这些控件全部在一个 内,其ACTION属性值是本页面,所以窗体的内容提交回本页面。在前面的章节的示例里使用了同样的技术。
在段中,改变属性或执行一个方法是通过一个按钮(没有标题)实现的。用于属性和方法的值放入按钮旁的文本框或列表框中。
该页的第一个按钮用于设定Dictionary里的条目的Key属性。这里使用了一个下拉列表,可以选择一个已经存在的Key值。下面的代码创建了页面内该部分的控件。为了填充列表,使用了另外一个遍历Dictionary对象的技术,即For Each ... Next语句。代码如下:
...
" METHOD="POST">

  

 

The Dictionary Properties
  
    Dictionary.Key ("
       ") = "
   "
  

  ...
  ... Other controls go here ...
  ...

...
4.  使用Dictionary的属性和方法
在"Scription.Dictionary Object"页面,点击用来检查并改变条目的Key属性的按钮,如图5-5所示:

把窗体再次提交给页面。该页面包含一个脚本段,检查被点击的按钮的值。它通过在Resquest.Form集合里查找按钮的名字来断定单击的是哪个按钮。如果发现一个对应于cmdChangKey的值,则从列表中或文本框中得到相应的值并用来改变Key属性:
...
'look for a command sent from the FORM section buttons
If Len(Request.Form("cmdChangeKey")) Then
    strKeyName = Request.Form("lstChangeKey")           'Existing key from list box
    strNewKey = Request.Form("txtChangeKey")            'New key value from text box
    objMyData.Key(strKeyName) = strNewKey               'Set key property of this item
End If
...
页面重新载入后,在Dictionary的内容列表里能看到相应的结果,如图5-6所示:

页面的其余代码用来设定一个条目的Item属性,或者执行Dictionary对象的方法。下面是这些操作的代码,每段代码与演示Key属性的代码非常类似。每次都将结果显示在Dictionary的内容列表中:
...
If Len(Request.Form("cmdChangeItem")) Then
    strKeyName = Request.Form("lstChangeItem")   'Existing key from list box
    strNewValue = Request.Form("txtChangeItem")   'New item value from text box
    objMyData.Item(strKeyName) = strNewValue     'Set the Item property
End If

If Len(Request.Form("cmdAdd")) Then
strKeyName = Request.Form("txtAddKey")         'New key value from text box
    strItemValue = Request.Form("txtAddItem")        'New item value from text box
    objMyData.Add strKeyName, strItemValue          'Execute the Add method
End If

If Len(Request.Form("cmdRemove")) Then
    strKeyName = Request.Form("lstRemove")         'Existion key from list box
    objMyData.Remove strKeyName                        'Execute the Remove method
End If

If Len(Request.Form("cmdRemoveAll")) Then
    objMyData.RemoveAll                                      'Execute the RemoveAll method
End If
...
例如,如果现在点击Add方法的按钮,在Dictionary的内容列表里将增加一个新的条目,如图5-7所示:

结果如图5-8所示:

可以在这个页面中试验Dictionary对象的属性和方法,你将会发现什么因素及在什么环境下能引起Dictionary对象错误。例如,尝试用与已经存在的一个条目相同的键值增加一个条目,看看会出现什么结果。

- 作者: mulin 2004年10月10日, 星期日 09:31  回复(0) |  引用(0) 加入博采

使用ADO GetChunk/AppendChunk 读写SQL Server BLOB字段
在设计数据库的过程中,我们会经常要存储一些图形、长文本、多媒体(视频、音频文件)等各种各样的程序文件,如果我们在数据库中仅存储这些文件的路径信息,尽管这可以大大地减小数据库的大小,但是由于文件存在磁盘上,我们除了维护数据库外还要维护文件的路径信息,保持二者的一致,这对于我们管理数据库非常不方便。我们还是寄希望能够把这些文件的内容作为一个记录的一个字段值存到数据库中,这样文件的上传和下载就变成了简单的字段读写。我们不用再考虑这些文件是如何在磁盘上存储的,数据库会帮我们做好一切工作。
SQL Server提供了多达2GB字节的字段类型(TEXT、IMAGE、NTEXT),这么大的空间可以说对于我们保存一般的文件已经足够了,我们可以把需要保存的虚拟光驱映象文件、MP3、AutoCAD图形、精美图片、RealPlayer视频音频文件等的内容存入到数据库中,根据用户检索的信息,再把对应的记录读出来,存到本地硬盘的一个临时文件中,然后用其对应的程序打开它,利用这种方法,我们可以实现在一个局域网中实现客户端的信息共享,也可以用这种方法做一个简单的视频点播系统,或者做一个WEB上传下载程序。但是由于这些文件的内容不是简单的文本信息,我们无法通过一般的粘贴和复制把它们写进去或者读出来,那么我们怎么才能读写这些二进制大字段(Binary Large Objects, BLOB)呢?
为了读写BLOB 字段,ADO为这些BLOB字段提供了两种方法GetChunk和AppendChunk,通过它们,你可以象读写文件一样,把其它文件的内容写进去读出来。

GetChunk方法
使用方法:variable = field.GetChunk( Size )
其中field为一个大文本或者二进制字段,size为要从该字段获得的字节或字符数。执行完将返回一个数据起始地址。由于系统限制,我们最好能够一部分一部分地从该字段获取数据,而不是整个把全部数据读出来。如果给定的size 大小大于该字段剩余没读出的的字节数,那么GetChunk仅返回剩余的数据;如果字段为空,将返回一个null值。
每一次顺序地调用GetChunk获取数据,都将从上一次读写没有读到的地方开始,然而如果你正从一个字段获取数据,然后又去设置或读取当前记录的另外一个字段,这样ADO就会认为你已经完成第一个字段的读取,如果你接着又读取第一个字段,ADO就会把这次调用视为一个新的GetChunk操作,将从数据的起始位置读写。如果你存取的是其它记录集对象,而且这个记录集不是第一个记录集的复制品,那么这个过程将不会打断GetChunk操作。
如果你想使用GetChunk方法读取一个字段,你必须把字段对象的Attributes属性的adFldLong位设置为真。如果你在一个没有当前记录的字段对象上使用GetChunk方法,将返回3021错误代码(没有当前记录)。
AppendChunk方法
使用方法:object.AppendChunk Dataobject 为一个字段或参数对象。
Data 为一个包含数据变量,这些数据将被追加到对象中。
同上面一样,如果你的系统内存有限,你尽可能分多次把数据追加到字段或参数对象。
如果你想使用AppendChunk 方法写一个字段,你需要把字段对象的字段Attributes属性的adFldLong位设置为真,第一次对一个字段对象使用AppendChunk方法,将会覆盖任何已有数据,后面调用AppendChunk将会把数据追加到存在数据的尾部。在向一个字段追加数据的时候,如果你又去设置或读取当前记录的另一个字段的值,ADO会认为你已经完成了对第一个字段的追加,再次对第一个字段调用AppendChunk方法,会被ADO解释为一次新的操作,从而覆盖已有数据。如果你存取的是其它记录集对象,而且这个记录集不是第一个记录集的复制品,那么这个过程将不会打断AppendChunk操作。如果你在一个没有当前记录的字段对象上使用AppendChunk方法,将返回错误信息(没有当前记录)。
下面是实现读写文件的过程例子,它已经被应用到一个学生管理系统,用于各个部门发布内部通知,通知的内容可以来自声音文件,视频文件,或者WORD文档,网页或电子表格、幻灯片等等,通知发布后,将作为一个记录存到数据库中,每个部门都可以下载到本地,进行察看浏览。这种方法可以广泛地应用到ASP中,开发上传或下载程序用
1.把文件内容写到数据库中
Const BLOCKSIZE As Long = 4096
Sub FileToColumn(Col As ADODB.Field, DiskFile As String)
'从一个临时文件中获取数据,并把它保存到数据库中
'col为一个ADO字段,DiskFile为一个文件名,它可以为一个远程文件。
Dim strData() As Byte '声明一个动态数组
Dim NumBlocks As Long '读写块数
Dim FileLength As Long '文件长度
Dim LeftOver As Long '剩余字节数
Dim SourceFile As Long ‘文件句柄
Dim i As Long
SourceFile = FreeFile '获得剩余的文件句柄号
Open DiskFile For Binary Access Read As SourceFile '以二进制读方式打开源文件。
FileLength = LOF(SourceFile) '获得文件长度
If FileLength = 0 Then
Close SourceFile '关闭文件
Peedy.Speak DiskFile & " Empty or Not Found." ‘调用Msagent控件,提示信息
Else
NumBlocks = FileLength / BLOCKSIZE ‘获得块数
LeftOver = FileLength Mod BLOCKSIZE ‘最后一块的字节数
Col.AppendChunk Null ‘追加空值,清除已有数据
ReDim strData(BLOCKSIZE) ‘从文件中读取内容并写到文件中。
For i = 1 To NumBlocks
Get SourceFile, , strData
Col.AppendChunk strData
Next I
ReDim strData(LeftOver)
Get SourceFile, , strData
Col.AppendChunk strData
Close SourceFile
End If
End Sub
 
2.从数据库中把文件内容读出来,并写到一个文件中。
 
Private Sub ColumnToFile(Col As ADODB.Field, DiskFile As String, rsset As Recordset)
'从数据库获得数据并把它们写到硬盘上的一个临时文件中。
'快的大小以4096为单位
 
Dim NumBlocks As Long '注释见上文
Dim LeftOver As Long '
Dim strData() As Byte
 
Dim DestFileNum As Long
Dim i As Long
Dim ColSize As Long
 
'确保你存取的不是一个空记录集
If Not rsset.EOF And Not rsset.BOF Then
ColSize = Col.ActualSize
'获得列的实际大小
'如果文件长度为零,将删除文件内容
If Len(Dir$(DiskFile)) > 0 Then
Kill DiskFile
End If
DestFileNum = FreeFile
Open DiskFile For Binary As DestFileNum
NumBlocks = ColSize / BLOCKSIZE
LeftOver = ColSize Mod BLOCKSIZE
'把数据写到文件中
For i = 1 To NumBlocks
ReDim strData(BLOCKSIZE)
strData = Col.GetChunk(BLOCKSIZE)
Put DestFileNum, , strData
Next i
 
ReDim strData(LeftOver)
strData = Col.GetChunk(LeftOver)
Put DestFileNum, , strData
Close DestFileNum
End If
End Sub
 
3.具体使用
只要在SQL Server2000中创建数据表时,设置字段类型为Image即可,浏览本地文件需调用ShellExecute函数。
ShellExecute Me.hWnd,"Open",szFileName, 0, 0, SW_SHOWNORMAL
本程序在Windows 2000环境下用Visual Basic 6和 SQL Server 2000 调试通过,采用的是Microsoft ADO Data Control 6.0控件。

- 作者: mulin 2004年10月8日, 星期五 11:21  回复(0) |  引用(0) 加入博采

数据库连接字符串,摘自www.connectionstrings.com
SQLServer
ODBC


Standard Security:

"Driver={SQL Server};Server=Aron1;Database=pubs;Uid=sa;Pwd=asdasd;"



Trusted connection:

"Driver={SQL Server};Server=Aron1;Database=pubs;Trusted_Connection=yes;"



Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Driver={SQL Server};Server=Aron1;DataBase=pubs;"



OLE DB, OleDbConnection (.NET)


Standard Security:

"Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"



Trusted Connection:

"Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"
(use serverName/instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)
Prompt for username and password:

oConn.Provider = "sqloledb"
oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Data Source=Aron1;Initial Catalog=pubs;"



Connect via an IP address:

"Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"
(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))
SqlConnection (.NET)


Standard Security:

"Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"
- or -
"Server=Aron1;Database=pubs;User ID=sa;Password=asdasd;Trusted_Connection=False"
(booth connection strings produces the same result)




Trusted Connection:

"Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"
- or -
"Server=Aron1;Database=pubs;Trusted_Connection=True;"
(booth connection strings produces the same result)

(use serverName/instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)
Connect via an IP address:

"Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"
(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))
Declare the SqlConnection:

C#:
using System.Data.SqlClient;
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString="my connectionstring";
oSQLConn.Open();



VB.NET:
Imports System.Data.SqlClient
Dim oSQLConn As SqlConnection = New SqlConnection()
oSQLConn.ConnectionString="my connectionstring"
oSQLConn.Open()



Data Shape


MS Data Shape
"Provider=MSDataShape;Data Provider=SQLOLEDB;Data Source=Aron1;Initial Catalog=pubs;User ID=sa;Password=asdasd;"
Want to learn data shaping? Check out 4GuyfFromRolla's great article about Data Shaping >>
Read more


How to define wich network protocol to use


Example:
"Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

Name Network library
dbnmpntw Win32 Named Pipes
dbmssocn Win32 Winsock TCP/IP
dbmsspxn Win32 SPX/IPX
dbmsvinn Win32 Banyan Vines
dbmsrpcn Win32 Multi-Protocol (Windows RPC)


Important note!
When connecting through the SQLOLEDB provider use the syntax Network Library=dbmssocn
and when connecting through MSDASQL provider use the syntax Network=dbmssocn


All SqlConnection connectionstring properties


This table shows all connectionstring properties for the ADO.NET SqlConnection object. Most of the properties are also used in ADO. All properties and descriptions is from msdn.

Name Default Description
Application Name The name of the application, or '.Net SqlClient Data Provider' if no application name is provided.
AttachDBFilename
-or-
extended properties
-or-
Initial File Name The name of the primary file, including the full path name, of an attachable database. The database name must be specified with the keyword 'database'.
Connect Timeout
-or-
Connection Timeout 15 The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
Connection Lifetime 0 When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. Useful in clustered configurations to force load balancing between a running server and a server just brought on-line.
Connection Reset 'true' Determines whether the database connection is reset when being removed from the pool. Setting to 'false' avoids making an additional server round-trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset.
Current Language The SQL Server Language record name.
Data Source
-or-
Server
-or-
Address
-or-
Addr
-or-
Network Address The name or network address of the instance of SQL Server to which to connect.
Enlist 'true' When true, the pooler automatically enlists the connection in the creation thread's current transaction context.
Initial Catalog
-or-
Database The name of the database.
Integrated Security
-or-
Trusted_Connection 'false' Whether the connection is to be a secure connection or not. Recognized values are 'true', 'false', and 'sspi', which is equivalent to 'true'.
Max Pool Size 100 The maximum number of connections allowed in the pool.
Min Pool Size 0 The minimum number of connections allowed in the pool.
Network Library
-or-
Net 'dbmssocn' The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP).
The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used.
Packet Size 8192 Size in bytes of the network packets used to communicate with an instance of SQL Server.
Password
-or-
Pwd The password for the SQL Server account logging on.
Persist Security Info 'false' When set to 'false', security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password.
Pooling 'true' When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool.
User ID The SQL Server login account.
Workstation ID the local computer name The name of the workstation connecting to SQL Server.


Note
Use ; to separate each property.
If a name occurs more than once, the value from the last one in the connectionstring will be used.
If you are building your connectionstring in your app using values from user input fields, make sure the user can't change the connectionstring by inserting an additional property with another value within the user value.
Access
ODBC


Standard Security:

"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:/mydatabase.mdb;Uid=Admin;Pwd=;"



Workgroup:

"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:/mydatabase.mdb;SystemDB=C:/mydatabase.mdw;"



Exclusive:

"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:/mydatabase.mdb;Exclusive=1;Uid=admin;Pwd="



OLE DB, OleDbConnection (.NET)


Standard security:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=/somepath/mydb.mdb;User Id=admin;Password=;"



Workgroup (system database):

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=/somepath/mydb.mdb;Jet OLEDB:System Database=system.mdw;"



With password:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=/somepath/mydb.mdb;Jet OLEDB:Database Password=MyDbPassword;"



Oracle
ODBC


New version:

"Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=Username;Pwd=asdasd;"



Old version:

"Driver={Microsoft ODBC Driver for Oracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;"



OLE DB, OleDbConnection (.NET)


Standard security:

"Provider=msdaora;Data Source=MyOracleDB;User Id=UserName;Password=asdasd;"
This one's from Microsoft, the following are from Oracle
Standard Security:

"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;User Id=Username;Password=asdasd;"



Trusted Connection:

"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;"



OracleConnection (.NET)


Standard:

"Data Source=Oracle8i;Integrated Security=yes;"
This one works only with Oracle 8i release 3 or later
Specifying username and password:

"Data Source=Oracle8i;User Id=username;Password=passwd;Integrated Security=no;"
This one works only with Oracle 8i release 3 or later
Declare the OracleConnection:

C#:
using System.Data.OracleClient;
OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "my connectionstring";
oOracleConn.Open();



VB.NET:
Imports System.Data.OracleClient
Dim oOracleConn As OracleConnection = New OracleConnection()
oOracleConn.ConnectionString = "my connectionstring"
oOracleConn.Open()



Core Labs OraDirect (.NET)


Standard:
"User ID=scott; Password=tiger; Host=ora; Pooling=true; Min Pool Size=0;Max Pool Size=100; Connection Lifetime=0"
Read more at Core Lab and the product page.
Data Shape


MS Data Shape:
"Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;Data Source=orac;user id=username;password=mypw"
Want to learn data shaping? Check out 4GuyfFromRolla's great article about Data Shaping >>
MySQL
ODBC


ODBC 2.50 Local database:

"Driver={mySQL};Server=localhost;Option=16834;Database=mydatabase;"



ODBC 2.50 Remote database:

"Driver={mySQL};Server=data.domain.com;Port=3306;Option=131072;Stmt=;Database=my-database;Uid=username;Pwd=password;"



ODBC 3.51 Local database:

"DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=myDatabase;USER=myUsername;PASSWORD=myPassword;OPTION=3;"



ODBC 3.51 Remote database:

"DRIVER={MySQL ODBC 3.51 Driver};SERVER=data.domain.com;PORT=3306;DATABASE=myDatabase;USER=myUsername;PASSWORD=myPassword;OPTION=3;"



OLE DB, OleDbConnection (.NET)


Standard:

"Provider=MySQLProv;Data Source=mydb;User Id=UserName;Password=asdasd;"
MySqlConnection (.NET)


eInfoDesigns.dbProvider:

"Data Source=server;Database=mydb;User ID=username;Password=pwd;Command Logging=false"
This one is used with eInfoDesigns dbProvider, an add-on to .NET
Declare the MySqlConnection:

C#:
using eInfoDesigns.dbProvider.MySqlClient;
MySqlConnection oMySqlConn = new MySqlConnection();
oMySqlConn.ConnectionString = "my connectionstring";
oMySqlConn.Open();



VB.NET:
Imports eInfoDesigns.dbProvider.MySqlClient
Dim oMySqlConn As MySqlConnection = New MySqlConnection()
oMySqlConn.ConnectionString = "my connectionstring"
oMySqlConn.Open()



SevenObjects MySqlClient (.NET)


Standard:

"Host=server; UserName=myusername; Password=mypassword;Database=mydb;"
This is a freeware ADO.Net data provider from SevenObjects
Core Labs MySQLDirect (.NET)


Standard:

"User ID=root; Password=pwd; Host=localhost; Port=3306; Database=test;Direct=true; Protocol=TCP; Compress=false; Pooling=true; Min Pool Size=0;Max Pool Size=100; Connection Lifetime=0"
Read more at Core Lab and the product page.
Interbase
ODBC, Easysoft


Local computer:

"Driver={Easysoft IB6 ODBC};Server=localhost;Database=localhost:C:/mydatabase.gdb;Uid=username;Pwd=password"



Remote Computer:

"Driver={Easysoft IB6 ODBC};Server=ComputerName;Database=ComputerName:C:/mydatabase.gdb;Uid=username;Pwd=password"
Read more about this driver: Easysoft ODBC-Interbase driver >>

ODBC, Intersolv


Local computer:

"Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};Server=localhost;Database=localhost:C:/mydatabase.gdb;Uid=username;Pwd=password"



Remote Computer:

"Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};Server=ComputerName;Database=ComputerName:C:/mydatabase.gdb;Uid=username;Pwd=password"
This driver are provided by DataDirect Technologies >> (formerly Intersolv)



OLE DB, SIBPROvider


Standard:

"provider=sibprovider;location=localhost:;data source=c:/databases/gdbs/mygdb.gdb;user id=SYSDBA;password=masterkey"



Specifying character set:

"provider=sibprovider;location=localhost:;data source=c:/databases/gdbs/mygdb.gdb;user id=SYSDBA;password=masterkey;character set=ISO8859_1"



Specifying role:

"provider=sibprovider;location=localhost:;data source=c:/databases/gdbs/mygdb.gdb;user id=SYSDBA;password=masterkey;role=DIGITADORES"
Read more about SIBPROvider >>




Read more about connecting to Interbase in this Borland Developer Network article http://community.borland.com/article/0,1410,27152,00.html


IBM DB2
OLE DB, OleDbConnection (.NET) from ms


TCP/IP:

"Provider=DB2OLEDB;Network Transport Library=TCPIP;Network Address=XXX.XXX.XXX.XXX;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"



APPC:

"Provider=DB2OLEDB;APPC Local LU Alias=MyAlias;APPC Remote LU Alias=MyRemote;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"



IBM's OLE DB Provider (shipped with IBM DB2 UDB v7 or above)


TCP/IP:

Provider=IBMDADB2;Database=sample;HOSTNAME=db2host;PROTOCOL=TCPIP;PORT=50000;uid=myUserName;pwd=myPwd;



ODBC


Standard:

"driver={IBM DB2 ODBC DRIVER};Database=myDbName;hostname=myServerName;port=myPortNum;protocol=TCPIP; uid=myUserName; pwd=myPwd"



Sybase
ODBC


Standard Sybase System 12 (or 12.5) Enterprise Open Client:

"Driver={SYBASE ASE ODBC Driver};Srvr=Aron1;Uid=username;Pwd=password"



Standard Sybase System 11:

"Driver={SYBASE SYSTEM 11};Srvr=Aron1;Uid=username;Pwd=password;"
Do you know a userguide for Sybase System 11, 12, 12.5? E-mail the URL to connectionstrings.com now!! >>
Intersolv 3.10:

"Driver={INTERSOLV 3.10 32-BIT Sybase};Srvr=Aron1;Uid=username;Pwd=password;"



Sybase SQL Anywhere (former Watcom SQL ODBC driver):

"ODBC; Driver=Sybase SQL Anywhere 5.0; DefaultDir=c:/dbfolder/;Dbf=c:/mydatabase.db;Uid=username;Pwd=password;Dsn="""""
Note! The two double quota following the DSN parameter at the end are escaped quotas (VB syntax), you may have to change this to your language specific escape syntax. The empty DSN parameter is indeed critical as not including it will result in error 7778.


Read more in the Sybase SQL Anywhere User Guide >>
OLE DB


Adaptive Server Anywhere (ASA):

"Provider=ASAProv;Data source=myASA"
Read more in the ASA User Guide >>
Adaptive Server Enterprise (ASE) with Data Source .IDS file:

"Provider=Sybase ASE OLE DB Provider; Data source=myASE"
Note that you must create a Data Source .IDS file using the Sybase Data Administrator. These .IDS files resemble ODBC DSNs.
Adaptive Server Enterprise (ASE):

"Provider=Sybase.ASEOLEDBProvider;Srvr=myASEserver,5000;Catalog=myDBname;User Id=username;Password=password"
- some reports on problem using the above one, try the following as an alternative -

"Provider=Sybase.ASEOLEDBProvider;Server Name=myASEserver,5000;Initial Catalog=myDBname;User Id=username;Password=password"
This one works only from Open Client 12.5 where the server port number feature works,燼llowing fully qualified connection strings to be used without defining燼ny .IDS Data Source files.
AseConnection (.NET)


Standard:

"Data Source='myASEserver';Port=5000;Database='myDBname';UID='username';PWD='password';"



Declare the AseConnection:

C#:
using Sybase.Data.AseClient;
AseConnection oCon = new AseConnection();
oCon.ConnectionString="my connection string";
oCon.Open();



VB.NET:
Imports System.Data.AseClient
Dim oCon As AseConnection = New AseConnection()
oCon.ConnectionString="my connection string"
oCon.Open()



Informix
ODBC


Informix 3.30:

"Dsn='';Driver={INFORMIX 3.30 32 BIT};Host=hostname;Server=myserver;Service=service-name;Protocol=olsoctcp;Database=mydb;UID=username;PWD=myPwd



Informix-CLI 2.5:

"Driver={Informix-CLI 2.5 (32 Bit)};Server=myserver;Database=mydb;Uid=username;Pwd=myPwd"



OLE DB


IBM Informix OLE DB Provider:

"Provider=Ifxoledbc.2;password=myPw;User ID=myUser;Data Source=dbName@serverName;Persist Security Info=true"



Ingres
ODBC


DSN-less

"Provider=MSDASQL.1;DRIVER=Ingres;SRVR=xxxxx;DB=xxxxx;Persist Security Info=False;uid=xxxx;pwd=xxxxx;SELECTLOOPS=N;Extended Properties="""SERVER=xxxxx;DATABASE=xxxxx;SERVERTYPE=INGRES""



Mimer SQL
ODBC


Standard Security:

"Driver={MIMER};Database=mydb;Uid=myuser;Pwd=mypw;"



Prompt for username and password:

"Driver={MIMER};Database=mydb;"



Lightbase
Standard


Standard:

"user=USERLOGIN;password=PASSWORD;UDB=USERBASE;server=SERVERNAME"



PostgreSQL
Core Labs PostgreSQLDirect (.NET)


Standard:

"User ID=root; Password=pwd; Host=localhost; Port=5432; Database=testdb;Pooling=true; Min Pool Size=0; Max Pool Size=100; Connection Lifetime=0"
Read more at Core Lab and the product page.



DSN
ODBC


DSN:

"DSN=myDsn;Uid=username;Pwd=;"



File DSN:

"FILEDSN=c:/myData.dsn;Uid=username;Pwd=;"



Firebird
ODBC - IBPhoenix Open Source


Standard:

"DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=masterkey;DBNAME=D:/FIREBIRD/examples/TEST.FDB"
IBPhoenix ODBC; More info, download etc >>
.NET - Firebird .Net Data Provider


Standard:

"User=SYSDBA;Password=masterkey;Database=SampleDatabase.fdb;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0"
Firebird ADO.NET project >>
Firebird ADO.NET downloads >>
Excel
ODBC


Standard:

"Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:/MyExcel.xls;DefaultDir=c:/mypath;"
TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.
OLE DB


Standard:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
"HDR=Yes;" indicates that the first row contains columnnames, not data
"IMEX=1;" tells the driver to always read "intermixed" data columns as text
TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.
Text
ODBC


Standard:

"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:/txtFilesFolder/;Extensions=asc,csv,tab,txt;"



OLE DB


Standard:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/txtFilesFolder/;Extended Properties=""text;HDR=Yes;FMT=Delimited"""
"HDR=Yes;" indicates that the first row contains columnnames, not data
DBF / FoxPro
ODBC


standard:

"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:/mydbpath;"



OLE DB, OleDbConnection (.NET)


standard:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/folder;Extended Properties=dBASE IV;User ID=Admin;Password="



AS/400
OLE DB


IBM Client Access OLE DB provider:

"PROVIDER=IBMDA400; DATA SOURCE=MY_SYSTEM_NAME;Uid=myUserName;Pwd=myPwd"
Where MY_SYSTEM_NAME is the name given to the system connection in OperationsNavigator
ODBC


IBM Client Access ODBC driver:

"Driver={Client Access ODBC Driver (32-bit)};System=my_system_name;Uid=myUserName;Pwd=myPwd"
Exchange
OLE DB


Exchange OLE DB provider:

"ExOLEDB.DataSource"
Specify store in the connection open command like this: conn.open "http://servername/mypublicstore"

Check out this article at msdn >> and this one at Addison-Wesley >>
Visual FoxPro
OLE DB, OleDbConnection (.NET)


Database container (.DBC):

"Provider=vfpoledb.1;Data Source=C:/MyDbFolder/MyDbContainer.dbc;Collating Sequence=machine"



Free table directory:

"Provider=vfpoledb.1;Data Source=C:/MyDataDirectory/;Collating Sequence=general"



Force the provider to use an ODBC DSN:

""Provider=vfpoledb.1;DSN=MyDSN""
Read more (Microsoft msdn) >>
ODBC


Database container (.DBC):

"Driver={Microsoft Visual FoxPro Driver};SourceType=DBC;SourceDB=c:/myvfpdb.dbc;Exclusive=No;NULL=NO;Collate=Machine;BACKGROUNDFETCH=NO;DELETED=NO"



Free Table directory:

"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=c:/myvfpdbfolder;Exclusive=No;Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO"
"Collate=Machine" is the default setting, for other settings check the list of supported collating sequences >>

Microsoft Visual Foxpro site: http://msdn.microsoft.com/vfoxpro


Pervasive
ODBC


Standard:

"Driver={Pervasive ODBC Client Interface};ServerName=srvname;dbq=@dbname"
Pervasive ODBC info >>
OLE DB


Standard:

"Provider=PervasiveOLEDB;Data Source=C:/path"
Pervasive OLE DB info >>
UDL

- 作者: mulin 2004年09月30日, 星期四 04:02  回复(1) |  引用(0) 加入博采

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值