不用数据源打开数据库(DSNless connection)

每一个需要联结数据库的程序,首先必须在服务器上打开它。这里有许多的办法!

使用系统数据源(DSN)
这个就必须在服务器上设置。这是数据访问最好最快的方法。因为它只需在服务器上认证一下就行了,不需要联结。

使用文件数据源
这不是一个值得推荐的方法。因为这样的话,所有的用户都被限制了!根本不适用于网络。

不需要DSN的联结
这种方法就不需要在服务器设置任何的东东,只要这个数据库存在就行!当然你也得有访问密码。
这是一个没有办法的办法,因为在服务器上没有DSN设置,而且速度也没有设置DSN快,因为每次都必须和服务器联结一次

微软有关于这方面的文章在
http://support.microsoft.com/support/kb/articles/q193/3/32.asp
在这里所有的DSNless联结代码。我们在这里只说一小部分,如果觉得我们说的不清楚就到那儿去看英文版吧!
哈哈。

DSNless联结需你知道数据库文件的名字(I.e. File based databases like Access, Paradox, FoxPro, etc.)或者数据库的服务器地址(SQL Server就是这样的)。还必须有打开这个数据库的权限,比如密码和用户名。有了这些你就可以打开这个数据库了!嘿嘿!

不过你要注意,如果你是用的Access数据库你就必须知道它的绝对路径,就像"C:\thatserver\account17\nwind.mdb"一样。不过Sever.MapPath方法能够将相对路径转为绝对路径。我们就不用担心了!

下面是一个例子例用了DSNless,用它来访问名叫nwind.mdb的Access的数据库。文件名为nwind.asp

1<html><head>
2<title>nwind.asp</title>
3<body bgcolor="#FFFFFF"></body></head>   

accessdb="nwind.mdb"
myDSN="DRIVER={Microsoft Access Driver (*.mdb)};"
myDSN=myDSN &amp; "DBQ=" &amp; server.mappath(accessdb)
mySQL="select * from customers"

call query2table(mySQL,myDSN)

1<!--#include virtual="/learn/test/lib_dbtable.asp"-->
2
3</html>

下面的例子是使用DSN来访问SQL Server,文件名为sqldsn.asp

1<html><head>
2<title>sqldsn.asp</title>
3<body bgcolor="#FFFFFF"></body></head>   

accessdb="nwind.mdb"
myDSN="DSN=student;uid=student;pwd=magic"
mySQL="select * from publishers where state='NY'"

call query2table(mySQL,myDSN)

1<!--#include virtual="/learn/test/lib_dbtable.asp"-->
2
3</html>

下面的例子是用DSNless来访问SQL Server数据库的方法。

1<html><head>
2<title>sqlDSNless.asp</title>
3<body bgcolor="#FFFFFF"></body></head>   

mydb="PROVIDER=MSDASQL;DRIVER={SQL Server};"
mydb=mydb &amp; "SERVER=sql2.datareturn.com;DATABASE=;"
mydb=mydb &amp; "UID=student;PWD=magic;"

mySQL="select * from publishers where state='NY'"

call query2table(mySQL,mydb)

1<!--#include virtual="/learn/test/lib_dbtable.asp"-->
2
3</html>

包含文件lib_dbtable.asp是以下的内容:

1   
2sub query2table(inputquery, inputDSN)   
3dim conntemp, rstemp   
4set conntemp=server.createobject("adodb.connection")   
5conntemp.open inputDSN   
6set rstemp=conntemp.execute(inputquery)   
7howmanyfields=rstemp.fields.count -1
1<table border="1"><tr>   

'Put Headings On The Table of Field Names
for I=0 to howmanyfields

1<td><b>```
2=rstemp(I).name
3```</b></td>   

next

1</tr>   

' Now lets grab all the records
do while not rstemp.eof

1<tr>   

for I = 0 to howmanyfields
thisvalue=rstemp(I)
If isnull(thisvalue) then
thisvalue=" "
end if

1<td valign="top">```
2=thisvalue
3```</td>   

next

1</tr>   

rstemp.movenext
loop

1</table>
1   
2rstemp.close   
3set rstemp=nothing   
4conntemp.close   
5set conntemp=nothing   
6end sub
Published At
Categories with Web编程
Tagged with
comments powered by Disqus