ASP中查詢數(shù)據(jù)庫記錄寫入XML文件示例
把下面代碼保存為Asp_XML.asp運(yùn)行即可:
<%
Const IsSql = 1 ’定義數(shù)據(jù)庫類型為SQL Server
Call OpenConn(Conn) ’打開數(shù)據(jù)庫連接
Dim Rs,Sql
Set Rs = Server.CreateObject("ADODB.RecordSet")
Sql = "SELECT * FROM Products ORDER BY ProductName"
Rs.Open Sql,Conn,1,1 ’以只讀方式查詢數(shù)據(jù)記錄
If Rs.Eof Then
Response.Write "Sorry,no record!" ’如果沒有記錄
Else
Dim objXMLDOM, objRootNode, objNode
Set objXMLDOM = Server.CreateObject("MSXML2.DOMDocument") ’創(chuàng)建XML文檔對象
Set objRootNode = objXMLDOM.createElement("xml") ’創(chuàng)建根節(jié)點(diǎn)
objXMLDOM.documentElement = objRootNode
Do While Not Rs.Eof ’循環(huán)出所有記錄
’ Response.Write Rs("ProductName") &"<br>"
Set objRowNode = objXMLDOM.createElement("row") ’創(chuàng)建父節(jié)點(diǎn)
Set objNode = objXMLDOM.createElement("ProductName") ’創(chuàng)建子節(jié)點(diǎn)
objNode.text = Rs("ProductName")
objRowNode.appendChild(objNode)
Set objNode = objXMLDOM.createElement("UnitPrice")
objNode.text = Rs("UnitPrice")
objRowNode.appendChild(objNode)
Set objNode = objXMLDOM.createElement("UnitsInStock")
objNode.text = Rs("UnitsInStock")
objRowNode.appendChild(objNode)
objRootNode.appendChild(objRowNode)
Rs.MoveNext:Loop ’循環(huán)結(jié)束
objXMLDOM.Save "D:\MyXMLDoc.xml" ’寫入XML文件 可以用變量讓用戶在頁面上自定義文件名
Response.Write "<script>alert(’恭喜,寫入XML文件成功!’);</script>"
Set objNode = Nothing ’銷毀對象
Set objRowNode = Nothing ’銷毀對象
Set objRootNode = Nothing ’銷毀對象
End If
Rs.Close
Set Rs = Nothing
Call CloseConn() ’關(guān)閉數(shù)據(jù)庫連接
Function OpenConn(Conn) ’打開數(shù)據(jù)庫連接
Dim ConnStr
If IsSql = 1 Then ’如果是SQL Server數(shù)據(jù)庫
’SQL Server數(shù)據(jù)庫連接參數(shù):用戶名、用戶密碼、數(shù)據(jù)庫名、連接名(本地用local,外地用IP)
Dim SqlUsername,SqlPassword,SqlDatabaseName,SqlLocalName
SqlUsername = "sa"
SqlPassword = ""
SqlDatabaseName = "Northwind"
SqlLocalName = "(local)"
ConnStr = "Provider = Sqloledb; User ID = " & SqlUsername & "; Password = " & SqlPassword & ";
Initial Catalog = " & SqlDatabaseName & "; Data Source = " & SqlLocalName & ";"
Else ’如果是Access數(shù)據(jù)庫
Dim Db
’第一次使用請修改本處數(shù)據(jù)庫地址并相應(yīng)修改數(shù)據(jù)庫名稱,如將Dicky.mdb修改為Dicky.asp(防止惡意下載Access數(shù)據(jù)庫)
Db = "Dicky.mdb"
ConnStr = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " & Server.MapPath(Db)
End If
On Error Resume Next
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnStr
If Err Then
’ Err.Clear
Set Conn = Nothing
Response.Write "數(shù)據(jù)庫連接出錯,請檢查連接字串。"
Response.End
End If
Set Rs = Server.CreateObject("Adodb.RecordSet")
End Function
Function CloseConn() ’關(guān)閉數(shù)據(jù)庫連接
Conn.Close
Set Conn = Nothing &
關(guān)鍵詞:ASP,XML文件
閱讀本文后您有什么感想? 已有 人給出評價!
- 1
- 1
- 1
- 1
- 1
- 1