เพิ่มบันทึก ADO

เราสามารถใช้คำสั่ง INSERT INTO ของ SQL เพื่อเพิ่มบันทึกลงในตารางของฐานข้อมูล

เพิ่มบันทึกลงในตารางของฐานข้อมูล

เราหวังที่จะเพิ่มบันทึกใหม่ลงในตาราง Customers ของฐานข้อมูล 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="เพิ่มใหม่"> 
<input type="reset" value="ยกเลิก">
</form>
</body>
</html>

เมื่อผู้ใช้กดปุ่มยืนยัน ฟอร์มนี้จะถูกส่งไปยังไฟล์ที่ชื่อ "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>

ความสำคัญ

ในขณะที่คุณใช้คำสั่ง INSERT command โปรดจำเป็นต่อไปนี้

  • หากตารางมีฟิลด์หลัก โปรดให้ความสุขุมให้ค่าที่เพิ่มเข้าไปในฟิลด์หลักเป็นค่าเดียวกันและไม่ว่าง (ถ้าไม่ได้ provider จะไม่เพิ่มบันทึกนี้ หรืออาจเกิดข้อผิดพลาด)
  • หากตารางมีฟิลด์ที่เป็นเลขประจำตัวอัตโนมัติ โปรดไม่ให้ใช้ฟิลด์นี้ในคำสั่ง INSERT (ค่าของฟิลด์นี้จะถูกจัดการโดย provider)

เกี่ยวกับฟิลด์ที่ไม่มีข้อมูล

ในฐานข้อมูล MS Access หากคุณกำหนดค่าของ AllowZeroLength ให้เป็น "Yes" คุณสามารถใส่ข้อมูลสตริงขนาด 0 ("") ในของที่เป็นข้อความ ลิงก์ และหมายเหตุ

หมายเหตุ:ไม่ทุกฐานข้อมูลเก็บข้อมูลสตริงขนาดเล็ก 0 จะสนับสนุนดังนั้น เมื่อเพิ่มบันทึกที่มีฟิลด์ว่าง อาจเกิดข้อผิดพลาดขึ้น ดังนั้น ตรวจสอบประเภทข้อมูลที่ฐานข้อมูลของคุณสนับสนุนเป็นสำคัญ