以下为引用的内容: <% Dim oConn,oRs Set oConn = Server.CreateObject("ADODB.Connection") Set ors = Server.CreateObject("ADODB.RecordSet") oConn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db1.mdb") Session("conn") = oConn ors.open "select * from t1",Session("conn"),1,1 Response.write(oRs(0)) ors.close Set ors = Nothing oConn.close Set oConn = Nothing %> |
这是网上流传的把Connection对象保存在Seesion对象中的代码,注意其中的:Session("conn") = oConn,对象的复制就是这样子的吗?下边我们来验证一下:
以下为引用的内容: <% Dim oConn,oRs Set oConn = Server.CreateObject("ADODB.Connection") Set ors = Server.CreateObject("ADODB.RecordSet") oConn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db1.mdb") Session("conn") = oConn ors.open "select * from t1",Session("conn"),1,1 Response.write(Session("conn").ConnectionString) ors.close Set ors = Nothing oConn.close Set oConn = Nothing %> |
结果出错,提示"缺少对象: 'Session(...)'"!这说明对象并没有复制成功,那Session("conn")是什么类型的呢?我们用TypeName(Session("conn"))来测试下,结果为"String"!出于好奇,我们直接输出Session("conn")看看:
以下为引用的内容: <% Dim oConn,oRs Set oConn = Server.CreateObject("ADODB.Connection") Set ors = Server.CreateObject("ADODB.RecordSet") oConn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db1.mdb") Session("conn") = oConn ors.open "select * from t1",Session("conn"),1,1 Response.write(Session("conn")) ors.close Set ors = Nothing oConn.close Set oConn = Nothing %> |
结果为:
以下为引用的内容:
Provider=Microsoft.Jet.OLEDB.4.0;Password="";User ID=Admin;Data Source=E:\www\db1.mdb;Mode=Share Deny None; |
这不是Connection对象的ConnectionString属性值吗?Connection对象默认的属性为ConnectionString,执行Session("conn") = oConn时只是将Connection对象默认属性的值赋给Session("conn")。那为什么用在oRs.open "select * from t1",Session("conn"),1,1也能成功呢?查找资料得出RecordSet对象open方法的第二个参数可以为Connection对象,也可以是数据库连接信息的字符串!Ok了,那在上边例子中的oConn对象完全是多余的,直接用下边代码即可:
以下为引用的内容: <% Dim ors Set ors = Server.CreateObject("ADODB.RecordSet") Session("conn") = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db1.mdb") ors.open "select * from t1",Session("conn"),1,1 Response.write(oRs(0)) ors.close Set ors = Nothing %> |
结果无错。好了,到现在为止还剩下一个问题没有解决:怎么才是正确的对象复制方法?还是用Set语句:
以下为引用的内容: <% Dim oConn,oRs Set oConn = Server.CreateObject("ADODB.Connection") Set ors = Server.CreateObject("ADODB.RecordSet") oConn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db1.mdb") Set Session("conn") = oConn ors.open "select * from t1",Session("conn"),1,1 Response.write(Session("conn").ConnectionString) Response.write("<br/>") Response.write(TypeName(Session("conn"))) ors.close Set ors = Nothing oConn.close Set oConn = Nothing %> |
这次能显示出ConnectionString属性的信息了,结果也显示Session("conn")为Connection对象!
原文:http://www.mzwu.com/article.asp?id=1105