ADO 添加記錄
我們可以使用 SQL 的 INSERT INTO 命令向數(shù)據(jù)庫中的表添加記錄。
向數(shù)據(jù)庫中的表添加記錄
我們希望向 Northwind 數(shù)據(jù)庫中的 Customers 表添加一條新的記錄。我們首先要?jiǎng)?chuàng)建一個(gè)表單,這個(gè)表單包含了我們需要從中搜集數(shù)據(jù)的輸入域:
<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> </tr><tr> <td>Contact Name:</td> <td><input name="contname"></td> </tr><tr> <td>Address:</td> <td><input name="address"></td> </tr><tr> <td>City:</td> <td><input name="city"></td> </tr><tr> <td>Postal Code:</td> <td><input name="postcode"></td> </tr><tr> <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>
當(dāng)用戶按下確認(rèn)按鈕時(shí),這個(gè)表單就會(huì)被送往名為 "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("No update permissions!") else Response.Write("<h3>" & recaffected & " record added</h3>") end if conn.close %> </body> </html>
重要事項(xiàng)
在您使用 INSERT command 命令時(shí),請注意以下事項(xiàng):
- 如果表含有一個(gè)主鍵,請確保向主鍵字段添加的值是唯一且非空的(否則,provider 就不會(huì)追加此記錄,亦或發(fā)生錯(cuò)誤)
- 如果表含有一個(gè)自動(dòng)編號的字段,請不要在 INSERT 命令中涉及此字段(這個(gè)字段的值是由 provider 負(fù)責(zé)的)
關(guān)于無數(shù)據(jù)字段
在 MS Access 數(shù)據(jù)庫中,假如您將 AllowZeroLength 屬性設(shè)置為 “Yes”,您可以在文本、超鏈接以及備忘字段輸入零長度的字符串 ("")。
注釋:并非所有的數(shù)據(jù)庫都支持零長度的字符串,因而當(dāng)添加帶有空白字段的記錄時(shí)可能會(huì)產(chǎn)生錯(cuò)誤。因此,檢查您使用的數(shù)據(jù)庫所支持的數(shù)據(jù)類型是很重要的。