Eisasuarez
Well-known Member
- Joined
- Mar 23, 2012
- Messages
- 653
Hi All,
I know you use recordsets to retrieve data using the SELECT statement.
I know you can use the connection or command promt to ammend the database i.e DELETE, INSERT etc...
I have seen people use the command or connection method but which is the best and preffered way so i can get in to a habbit of doing it the right way.
I know you use recordsets to retrieve data using the SELECT statement.
I know you can use the connection or command promt to ammend the database i.e DELETE, INSERT etc...
I have seen people use the command or connection method but which is the best and preffered way so i can get in to a habbit of doing it the right way.
Code:
Sub Connect_Database()
Dim cmd As ADODB.Command
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strDBPath As String
Set ws = Sheets("Sheet1")
strDBPath = "C:\Users\Matt\Desktop\Excel VBA Examples\VBA Examples\VBA 2010\SampleDatabase3.accdb"
connection_string = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
[COLOR=#ff0000] ' The below SQL string would and should only be used in a Recordset as we are retrieving Data[/COLOR]
[COLOR=#ff0000] 'strSQL = "SELECT * FROM users WHERE tblactor LIKE 'A*'"[/COLOR]
[COLOR=#ff0000] ' The method below could use the command or connection method to execute as we are ammending the database[/COLOR]
[COLOR=#ff0000] strSQL = "UPDATE [users] SET [UserName]='Matthew Martell' WHERE [UserID]='MATTHEW'"[/COLOR]
'//Connetion method to Open and execute SQL string
Set cn = New ADODB.Connection
With cn
.ConnectionString = connection_string
.Open
[COLOR=#0000ff] .Execute strSQL[/COLOR]
End With
'// Command method to execute SQL string
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = cn
.CommandType = adCmdText
.CommandText = strSQL
[COLOR=#0000ff] .Execute[/COLOR]
End With
End Sub