Possiamo utilizzare INSERT INTO SQL comando per aggiungere un record a una tabella in un database.
Aggiungere un record a una tabella in un database
Vogliamo aggiungere un nuovo record alla tabella Customers del database Northwind. Per prima cosa creare un modulo che contiene i campi che vogliamo raccogliere i dati da:
<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>
Quando l'utente preme il pulsante di invio del modulo viene inviato a un file chiamato "demo_add.asp" . Il "demo_add.asp" file contiene il codice che aggiungerà un nuovo record alla tabella Clienti:
<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>
Importante
Se si utilizza il comando SQL INSERT essere a conoscenza di quanto segue:
- Se la tabella contiene una chiave primaria, assicurarsi di aggiungere un valore non nullo unica per il campo chiave primaria (in caso contrario, il provider non può accodare il record, o si verifica un errore)
- Se la tabella contiene un campo Contatore, non includere questo settore nel comando SQL INSERT (il valore di questo campo verrà curato automaticamente dal provider)
Che dire di campi senza dati?
In un database di MS Access, è possibile inserire stringhe di lunghezza zero ("") nel testo, hyperlink, e campi Memo se si imposta la proprietà AllowZeroLength su Sì.
Note: Non tutti i database supportano stringhe di lunghezza zero e può causare un errore quando si aggiunge un record con campi vuoti. E 'importante verificare quali tipi di dati supporta il database.