how do i add records and delete them via code?
Printable View
how do i add records and delete them via code?
Try this:
Using Database and Recordset objects for DAO or
Connection and Recordset abjects ADO.
Move to the record that you want to delete by using either
one of the move methods (movefirst, moveprevious, movenext, movelast) or the findfirst/find method.
The just call the delete method, as in: recordset.Delete
and do you have any code that would help?
This is just a basic guide.Code:
Dim cnnDB as new ADODB.connection
Dim rstTemp as new ADODB.recordset
Dim strCnn as string
'Connect to a local database using Jet
strCnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp.mdb;"
cnnDB.Mode = adModeShareDenyNone
cnnDB.Open StrCnn
'Open a recordset
rstTemp.open "SELECT * FROM temp", cnnDB
'Add a record
With rstTemp
.addNew
!Field1 = Value1
!Field2 = Value 2
'and so on
End With
'To delete the current record
rstTemp.delete
'After either of these methods you should call
rstTemp.update
'Clean up
rstTemp.close
cnnDB.close
Set rstTemp = Nothing
Set cnnDB = Nothing
www.microsoft.com/data
has more info under the ADO section
Code:Option Explicit
Public cDBName As String
Public cTblName As String
Public Sub OpenDB()
Dim db As Database, rs As Recordset
Dim AppPath$
If Right(App.Path, 1) <> "\" Then _
AppPath = App.Path & "\" _
Else AppPath = App.Path
cDBName = AppPath & "YourDatabaseName.mdb"
cTblName = "YourTable"
Set db = Workspaces(0).OpenDatabase(cDBName)
Set rs = db.OpenRecordset(cTblName)
Data1.DatabaseName = cDBName
Data1.RecordSource = cTblName
Data1.Refresh
End Sub
Private Sub Command1_Click()
Data1.Recordset.AddNew
Data1.Recordset!YourField = Text1.Text
Data1.Recordset.Update
Data1.Refresh
Command1.Enabled = False
End Sub
Private Sub Form_Activate()
'
Call OpenDB
'
Form1.Data1.Recordset.movefirst
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''
' sub to process delete function in a database
' once you are at the position on the record
'call this routine to do delete a record from your database
Public Sub DeleteRec()
'
' give user option of deleting or escaping from delete function
' datName is the name of my data control
' RecordCount is a global variable containing the recordcount
Dim intRtn
'
intRtn = MsgBox("Do you really wish to delete this record?", _
vbYesNo, "Delete Function")
' if user wishes to delete then delete and move to previous record
'
If intRtn = 6 Then
datName.Recordset.Delete
If datName.Recordset.AbsolutePosition + 1 = datName.Recordset.RecordCount Then
datName.Recordset.MovePrevious
Else
datName.Recordset.MoveNext
End If
Else
Exit Sub 'if user wishes to escape the function...quit sub
'
End If
'
'call from event on form
Call DeleteRec
thank you very much for your help