2014/12/01

How to connect to Sql Server local database file (localDB) with VBA ?

Sub run()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlStr As String
Dim dbFilePath As String
Dim dbName As String
dbName = "DbInjectorsCatalog"
dbFilePath = "C:\Users\marcinchyl\Desktop\Marcin2\Projects\InjectorsCatalog\Admin\DbInjectorsCatalog.mdf"
connStr = "Driver={SQL Server native Client 11.0};Server=(LocalDB)\v11.0;AttachDBFileName=" & dbFilePath & ";Database=" & dbName & ";Trusted_Connection=Yes"
sqlStr = "Select * from Injectors"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
conn.Open
Set rs = conn.Execute(sqlStr)
Do While Not rs.EOF
Debug.Print rs!Number
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Sub
view raw gistfile1.vb hosted with ❤ by GitHub

4 comments:

  1. how we will do if we want to amke this connection global and use that object in other subs as well

    ReplyDelete
    Replies
    1. Sorry for such a late answer
      I think we should do..

      Delete
  2. Could you please let me know the software installation required to support this driver?

    ReplyDelete
    Replies
    1. Sorry for such a late answer
      I do not remember but you need to add one or two references to dlls in VBA editor

      Delete