ADO Aggiungi record


Possiamo usare il comando SQL INSERT INTO per aggiungere un record a una tabella in un database. 


Aggiungi un record a una tabella in un database

Si desidera aggiungere un nuovo record alla tabella Clienti nel database Northwind. Per prima cosa creiamo un modulo che contiene i campi da cui vogliamo raccogliere i dati:

<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, il modulo viene inviato a un file chiamato "demo_add.asp". Il file "demo_add.asp" 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 utilizzi il comando SQL INSERT, tieni presente quanto segue:

  • Se la tabella contiene una chiave primaria, assicurati di aggiungere un valore univoco non Null al campo della chiave primaria (in caso contrario, il provider potrebbe non aggiungere il record o si verificherà un errore)
  • Se la tabella contiene un campo AutoNumber, non includere questo campo nel comando SQL INSERT (il valore di questo campo sarà curato automaticamente dal provider)

E i campi senza dati?

In un database di MS Access, è possibile immettere stringhe di lunghezza zero ("") nei campi Testo, Collegamento ipertestuale e Memo SE si imposta la proprietà AllowZeroLength su Sì.

Nota: non tutti i database supportano stringhe di lunghezza zero e possono causare un errore quando viene aggiunto un record con campi vuoti. È importante verificare quali tipi di dati sono supportati dal database.