|
|
Title | Loop through database records and modify them individually |
Keywords | database, ADO, update, records |
Categories | Database |
|
|
Select the records to modify into an ADO Recordset. Loop through the records.
For each record, modify the record's field values and call the Recordset's
Update method to save the changes.
Note that this is not the best way to update records if you want to make the same change to every record.
For example, if you want to add an X to each Title field, use the SQL statement:
UPDATE Books SET Title = "X" + Title
|
|
' Add a number to the beginning of each book title.
Private Sub cmdAddNumbers_Click()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim num As Integer
' Open the Connection.
Set conn = New ADODB.Connection
conn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & DbFile & ";" & _
"Persist Security Info=False"
conn.Open
' Open the Recordset.
Set rs = New ADODB.Recordset
rs.Open Source:="Books", _
ActiveConnection:=conn, _
CursorType:=adOpenDynamic, _
LockType:=adLockOptimistic
' List the data.
num = 1
Do While Not rs.EOF
' See if the title already includes a period.
If InStr(rs!Title, ".") = 0 Then
' Add a number to the book title.
rs!Title = Format$(num) & ". " & rs!Title
rs.Update
End If
' Move to the next record.
num = num + 1
rs.MoveNext
Loop
rs.Close
conn.Close
' Redisplay the new data.
ListData
End Sub
' Remove numbers from the beginning of each book title.
Private Sub cmdRemoveNumbers_Click()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim pos As Integer
' Open the Connection.
Set conn = New ADODB.Connection
conn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & DbFile & ";" & _
"Persist Security Info=False"
conn.Open
' Open the Recordset.
Set rs = New ADODB.Recordset
rs.Open Source:="Books", _
ActiveConnection:=conn, _
CursorType:=adOpenDynamic, _
LockType:=adLockOptimistic
' List the data.
Do While Not rs.EOF
' Find the . after the number.
pos = InStr(rs!Title, ".")
' Remove the . and the following space.
If pos > 0 Then
rs!Title = Mid$(rs!Title, pos + 2)
rs.Update
End If
' Move to the next record.
rs.MoveNext
Loop
rs.Close
conn.Close
' Redisplay the new data.
ListData
End Sub
|
|
|
|
|
|