ADO เพิ่มระเบียน
เราอาจใช้คำสั่ง SQL INSERT INTO เพื่อเพิ่มบันทึกลงในตารางในฐานข้อมูล
เพิ่มบันทึกลงในตารางในฐานข้อมูล
เราต้องการเพิ่มระเบียนใหม่ลงในตารางลูกค้าในฐานข้อมูล Northwind ขั้นแรก เราสร้างแบบฟอร์มที่มีฟิลด์ที่เราต้องการรวบรวมข้อมูลจาก:
<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>
เมื่อผู้ใช้กดปุ่มส่ง แบบฟอร์มจะถูกส่งไปยังไฟล์ชื่อ "demo_add.asp" ไฟล์ "demo_add.asp" มีรหัสที่จะเพิ่มระเบียนใหม่ลงในตารางลูกค้า:
<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>
สำคัญ
หากคุณใช้คำสั่ง SQL INSERT โปรดระวังสิ่งต่อไปนี้:
- หากตารางมีคีย์หลัก ตรวจสอบให้แน่ใจว่าได้ผนวกค่าที่ไม่ซ้ำกันและไม่ใช่ Null ลงในฟิลด์คีย์หลัก (หากไม่ใช่ ผู้ให้บริการอาจไม่ผนวกเร็กคอร์ด หรือมีข้อผิดพลาดเกิดขึ้น)
- หากตารางมีฟิลด์ AutoNumber ให้ไม่รวมฟิลด์นี้ในคำสั่ง SQL INSERT (ผู้ให้บริการจะดูแลค่าของฟิลด์นี้โดยอัตโนมัติ)
แล้วฟิลด์ที่ไม่มีข้อมูลล่ะ?
ในฐานข้อมูล MS Access คุณสามารถป้อนสตริงที่มีความยาวเป็นศูนย์ ("") ในช่องข้อความ ไฮเปอร์ลิงก์ และบันทึกช่วยจำ หากคุณตั้งค่าคุณสมบัติ AllowZeroLength เป็น ใช่
หมายเหตุ:ฐานข้อมูลบางฐานข้อมูลไม่สนับสนุนสตริงที่มีความยาวเป็นศูนย์ และอาจทำให้เกิดข้อผิดพลาดเมื่อมีการเพิ่มเรกคอร์ดที่มีฟิลด์ว่าง สิ่งสำคัญคือต้องตรวจสอบว่าฐานข้อมูลของคุณรองรับประเภทข้อมูลใดบ้าง