Asp數(shù)據(jù)庫(kù)操作教學(xué)代碼(原創(chuàng))
首先要保證已經(jīng)安裝了IIS,有問(wèn)題再說(shuō)。
讀寫(xiě)數(shù)據(jù)庫(kù)代碼:
<%
'建立Connection和RecordSet對(duì)象
Set Cnn = Server.CreateObject("Adodb.Connection")
Set Rs = Server.CreateObject("Adodb.Recordset")
'打開(kāi)數(shù)據(jù)庫(kù)
Cnn.Open "Driver={Microsoft Access Driver (*.mdb)};dbq="&Server.MapPath("與當(dāng)前頁(yè)面相對(duì)地址下的Access文件名")
'注釋?zhuān)?br />'連接sql server數(shù)據(jù)庫(kù)為
'Cnn.Open "Driver={Sql Server};server=數(shù)據(jù)庫(kù)服務(wù)器地址;uid=用戶(hù)名;pwd=密碼;datebase=缺省的數(shù)據(jù)庫(kù)"
'連接ODBC為,如果用戶(hù)名或者密碼為空,直接用兩個(gè)連續(xù)的雙引號(hào)""表示為空
'Cnn.Open "ODBC DSN名稱(chēng)","用戶(hù)名","密碼"
'打開(kāi)數(shù)據(jù)表
sql="Select * from 表名"
'1和3的意思你應(yīng)該知道,如果不清楚所有的情況就用這兩個(gè)參數(shù)就行了。
Rs.Open sql,Cnn,1,3
'判斷數(shù)據(jù)庫(kù)是否為空
If Rs.eof Then
Response.Write "數(shù)據(jù)庫(kù)為空。"
End if
'在數(shù)據(jù)表里添加空行
Rs.AddNew
'給空行寫(xiě)入數(shù)據(jù)
Rs("Name")="YangYang"
Rs("Pass")="yangyang"
'別忘了更新一下
Rs.Update
'修改記錄,和添加記錄類(lèi)似,只是沒(méi)有了Rs.AddNew
'刪除數(shù)據(jù)表中的當(dāng)前行
Rs.Delete
'也可以用Sql語(yǔ)句操作數(shù)據(jù)庫(kù),假設(shè)數(shù)據(jù)表叫Users,里面有User,Pass,Time三個(gè)字段
'用Sql插入記錄
strUser="Yang"
strPass="Zhao"
strTime=now()? '注釋?zhuān)寒?dāng)前時(shí)間
sql="Insert Into Users (User,Name,Time) Values ('"&strUser&"','"&strPass&"','"&strTime&"')"
Cnn.Execute(Sql)
'用Sql刪除記錄
Sql="Delete Users Where User='"&strUser&"'"
Cnn.Execute(sql)
'用Sql修改記錄
Sql="Update Users Set Pass='abcd' Where User='Yang'"
Cnn.Execute(sql)
'循環(huán)在網(wǎng)頁(yè)上打印所有數(shù)據(jù)
Do Until(rs.eof)
'key可以是字段的順序號(hào)(從1開(kāi)始),也可以是字段名稱(chēng),字段名稱(chēng)要用雙引號(hào)引起來(lái)。
Response.write Rs(key1)&RS(key2)
Rs.Next
Loop
'關(guān)閉表對(duì)象和連接對(duì)象
Rs.Close
Set Rs = Nothing
Cnn.close
Set Cnn = Nothing
%>