ADO 新增記錄
我們可以使用 SQL INSERT INTO 命令向資料庫中的表中新增一條記錄。
向資料庫表中新增一條記錄
我們要向 Northwind 資料庫的 Customers 表中新增一條新記錄。我們首先建立一個包含我們要收集資料欄位的表單
<html>
<body>
<form method="post" action="demo_add.asp">
<table>
<tr>
<td>客戶 ID:</td>
<td><input name="custid"></td>
</tr><tr>
<td>公司名稱:</td>
<td><input name="compname"></td>
</tr><tr>
<td>聯絡人姓名:</td>
<td><input name="contname"></td>
</tr><tr>
<td>地址:</td>
<td><input name="address"></td>
</tr><tr>
<td>城市:</td>
<td><input name="city"></td>
</tr><tr>
<td>郵政編碼:</td>
<td><input name="postcode"></td>
</tr><tr>
<td>國家:</td>
<td><input name="country"></td>
</tr>
</table>
<br><br>
<input type="submit" value="新增新記錄">
<input type="reset" value="取消">
</form>
</body>
</html>
當用戶按下提交按鈕時,表單會被髮送到一個名為 "demo_add.asp" 的檔案。 "demo_add.asp" 檔案包含將新記錄新增到 Customers 表的程式碼。
<html>
<body>
<%
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("沒有更新許可權!")
else
Response.Write("<h3>" & recaffected & " 條記錄已新增</h3>")
end if
conn.close
%>
</body>
</html>
重要
如果您使用 SQL INSERT 命令,請注意以下事項:
- 如果表包含主鍵,請確保為該主鍵欄位新增一個唯一、非 Null 的值(否則,提供程式可能不會新增記錄,或者會發生錯誤)。
- 如果表包含 AutoNumber 欄位,請不要在 SQL INSERT 命令中包含此欄位(該欄位的值將由提供程式自動處理)。
沒有資料的欄位怎麼辦?
在 MS Access 資料庫中,如果將 AllowZeroLength 屬性設定為 Yes,您可以在文字、超連結和備忘錄欄位中輸入零長度字串 ("")。
注意:並非所有資料庫都支援零長度字串,並且在新增帶有空白欄位的記錄時可能會導致錯誤。檢查您的資料庫支援的資料型別非常重要。