我們可以使用 SQL 的 INSERT INTO 指令向資料庫中的表添加記錄。
我們希望向 Northwind 資料庫中的 Customers 表添加一條新的記錄。我們首先要建立一個表單,這個表單包含了我們需要從中搜集資料的輸入域:
<html>
<body>
<form method="post" action="demo_add.asp">
<table>
<tr>
<td>CustomerID:</td>
<td><input name="custid"></td>
</tr><tr>
<td>Company Name:</td>
<td><input name="compname"></td>
<td>Contact Name:</td>
<td><input name="contname"></td>
<td>Address:</td>
<td><input name="address"></td>
<td>City:</td>
<td><input name="city"></td>
<td>Postal Code:</td>
<td><input name="postcode"></td>
<td>Country:</td>
<td><input name="country"></td>
</tr>
</table>
<br><br>
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>
</body>
</html>
當使用者按下确認按鈕時,這個表單就會被送往名為 "demo_add.asp" 的檔案。檔案 "demo_add.asp" 中含有可向 Customers 表添加一條新記錄的代碼:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
sql="INSERT INTO customers (customerID,companyname,"
sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
%>
在您使用 INSERT command 指令時,請注意以下事項:
如果表含有一個主鍵,請確定向主鍵字段添加的值是唯一且非空的(否則,provider 就不會追加此記錄,亦或發生錯誤)
如果表含有一個自動編号的字段,請不要在 INSERT 指令中涉及此字段(這個字段的值是由 provider 負責的)
在 MS Access 資料庫中,假如您将 AllowZeroLength 屬性設定為 "Yes",您可以在文本、超連結以及備忘字段輸入零長度的字元串 ("")。
注釋:并非所有的資料庫都支援零長度的字元串,因而當添加帶有空白字段的記錄時可能會産生錯誤。是以,檢查您使用的資料庫所支援的資料類型是很重要的。