Lesson 22: Update data in a database

In previous lessons, you have learned to retrieve, insert and delete data from a database. In this lesson, we will look at how to update a database, i.e. edit the values of existing fields in the table.

Update data with SQL

The syntax for an SQL statement that updates the fields in a table is:

Update TableName Set TableColumn='value' Where condition

It is also possible to update multiple cells at once using the same SQL statement:

Update TableName Set TableColumn1='value1', TableColumn2='value2' Where condition

With the knowledge you now have from the lessons 19, 20 and 21, it should be quite easy to understand how the above syntax is used in practice. But we will of course look at an example.

Example: Update cells in the table "people"

The code below updates Donald Duck's first name to D. and changes the phone number to 44444444 The other information (last name and birthdate) are not changed. You can try to change the other people's data by writing your own SQL statements.


	<html>
	<head>
	<title>Update data in database</title>

	</head>
	<body>
	<%
	' Database connection - remember to specify the path to your database

	Set Conn = Server.CreateObject("ADODB.Connection")
	DSN = "DRIVER={Microsoft Access Driver (*.mdb)}; "
	DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")

	Conn.Open DSN

	' The SQL statement is built
	strSQL = "Update people set " 
	strSQL = strSQL & "FirstName= 'D.', " 
	strSQL = strSQL & "Phone= '44444444' " 

	strSQL = strSQL & "Where Id = 24" 

	' The SQL statement is executed 
	Conn.Execute(strSQL)

	' Close the database connection
	Conn.Close

	Set Conn = Nothing
	%>
	<h1>The database is updated!</h1>
	</body>
	</html>

	
	

This example completes the lessons on databases. You have learned to retrieve, insert, delete and update a database with ASP. Thus, you are actually now able to make very advanced and dynamic web solutions, where the users can maintain and update a database using forms.

If you want to see a sophisticated example of what can be made with ASP and databases, try to join our community. It's free and takes approximately one minute to sign up. You can, among other things, maintain your own profile using the form fields. Maybe you will get ideas for your own site. (Note: HTML.net is coded in PHP but could have been made in ASP).

ASP gives you many possibilities for adding interactivity to your web site. The only limit is your imagination - have fun!



<< Lesson 21: Delete data from a database