2014-02-12 3 views
0

Access 2003/SQL Server - Access 2003 MDB (Connect 속성)를 업데이트하여 다른 SQL Server 데이터베이스를 가리킬 수 있습니까? 새 SQL Server 데이터베이스는 이전 인스턴스와 동일한 인스턴스에 있습니다.다른 SQL Server 데이터베이스를 가리 키도록 Access 2003 MDB를 업데이트하십시오.

+0

당신은 원하는 연결 테이블 관리 (http://www.techonthenet.com/access/tables/refresh_links.php) 또는 vba를 사용할 수 있습니까? – Fionnuala

+0

또한 패스 스루 쿼리에서 속성 창을 사용하여 다른 SQL Server에 대한 새 ODBC 연결을 선택할 수 있지만 새 ODBC 연결을 만들거나 이전 쿼리를 업데이트해야합니다 (이전 쿼리를 업데이트 한 경우 ' t는 바뀔 필요가있다, 나는 thnk). – bf2020

답변

0

나는 내가 관리하는 여러 MS Access 2003/SQL Server 응용 프로그램이 있습니다. 모두가 시작할 때 올바른 데이터베이스에 동적으로 연결됩니다. 그 중 일부는 시작 시퀀스 중에 여러 서버의 여러 데이터베이스에 연결됩니다. 이들 모두는 동일한 기본 vba 루틴을 사용하여 테이블을 실제로 올바른 서버에 연결합니다. 이것은 내 코드가 아니며 인터넷을 통해 인터넷으로 찾았지만 지금은 그에 대한 참조를 잃어 버렸기 때문에 미리 저자들에게 사과합니다.

컨텍스트에 넣기 전에 코드를 표시하기 전에 일반적으로 "frmInitApp"형식의 "config"라는 필드가있는 로컬 구성 테이블 인 데이터 소스가 있습니다. "ID = 1"필터를 사용하여이 양식을 여는 AutoExec 매크로에서 액세스 응용 프로그램을 시작합니다. 이 구성 테이블을 조작하고 ID를 변경하는 다른 양식이 있으므로 프로덕션과 테스트 사이를 전환하려면 ID가 1 인 항목을 변경하십시오.

SQL Server에 동적으로 연결할 Access 테이블의 목록이있는 다른 로컬 테이블 tableList가 있습니다. 대부분의 응용 프로그램은 SQL Server 테이블 이름에 대해이 테이블에 다른 필드를 가지고 있으므로 (동일 할 필요는 없습니다) - 일부 응용 프로그램에는 데이터베이스를 지정하는 추가 필드가 있습니다. 하지만 더 복잡한 다른 스파게티가 필요합니다 - 나는 종종 다른 데이터베이스에 연결 문자열의 다른 테이블로 끝날 것입니다. 기타 등등에 연결할 수도 있습니다. 간단하게 유지하려면 config 테이블의 필드에 연결 문자열이 있어야합니다. frmInitApp에 ​​대한 데이터 소스입니다.

frmInitApp에서 현재 이벤트를 시작합니다.

그리고 나서 우리는 테이블의 기능을 통해 테이블에 연결할 수 있습니다. 우리는 또한 쿼리를 통과시켜 새로운 데이터베이스를 가리킬 수 있도록 다시 연결합니다. 또한 우리는 첫 번째 테이블에 연결하자마자 한 명의 사용자로 로그인하여 새로운 양식을 엽니 다. 나는 어쨌든 그 모든 것이 끝났을 때 첨부 된 테이블에 대해 사용자 이름과 패스워드를 검증 할 필요가있는 결론을 보여주지는 않지만 어쨌든 알아내는 것은 쉽지 않다.

Private Sub Form_Timer() 
    Dim conn As ADODB.Connection 
    Dim dbRs As ADODB.Recordset 
    Dim dbOK As Boolean 
    Dim SQL As String 

    Dim startedLogon As Boolean 
    Me.TimerInterval = 0 
    Select Case Me.stage 
    Case "InitialStartup" 
     Set conn = CurrentProject.Connection 
     startedLogon = False 
     If CurrentProject.AllForms("frmLogon").IsLoaded Then 
      'If its already loaded this NOT the first time through, but still need to logon ... 
      If Form_frmLogon.configID = configID Then 
       startedLogon = True 'unless its the same config 
      End If 
     End If 
     dbOK = True 
     Set dbRs = New ADODB.Recordset 
     dbRs.Open "SELECT localname,servername FROM tableList", conn 
     While dbOK And Not dbRs.EOF 
     'PLEASE NOTE - WHILST THEORETICALLY "localname" and "servername" could be different the migration process 
     'requires that they be the same. Do not consider changing this until after migration is completed 

      dbOK = AttachTable(dbRs("localname"), "dbo." & dbRs("servername")) 
      dbRs.MoveNext 
      If Not startedLogon And dbOK Then 
       DoCmd.Close acForm, "frmLogon"  '#554 Just in case its alread open - we need to pick up new params 
       DoCmd.OpenForm "frmLogon", , , , , , Nz(Me.lastUserId, "") & ":" & configID 
       Form_frmLogon.SetFocus    '#748 Give it focus 
       startedLogon = True 
      End If 
     Wend 
     dbRs.Close 
     If dbOK Then 

      Me.messages = "Relinking Common Queries ..." 
      DoEvents 

      Dim qd As DAO.QueryDef, cs As String 

      cs = getStrConnDAO 'get the DAO connection string 
      For Each qd In CurrentDb.QueryDefs 
       If Len(qd.Connect & vbNullString) > 0 Then 
        qd.Connect = cs 
       End If 
      Next 

     End If 
     Me.messages = "Awaiting User Log On" 
     DoCmd.Hourglass False 
     DoEvents 
     ... the rest just managing logon 
End Sub 

당신은 getConStrDAO 기능에

Private ADOconnStr As String 
Private DAOconnStr As String 
Public Function getStrConn(Optional configID As Long = 0) As String 
    'create a connection string for use when running stored procedures 
    'this uses the saved value if possible, but global variables are reset if an error occurs 
    If ADOconnStr = "" Then 
     Dim conn As ADODB.Connection 
     Dim rs As ADODB.Recordset 
     Dim account As String 
     Dim revealedPassword As String 
     Dim s As String, i As Integer, x As String 
     Set conn = CurrentProject.Connection 
     If configID = 0 Then configID = Nz(Form_frmLogon.configID, 0) 
     Set rs = conn.Execute("SELECT * FROM localConfig WHERE id =" & configID) 
     If Not rs.EOF Then 
      ADOconnStr = "Provider=Microsoft.Access.OLEDB.10.0;Data Provider=SQLOLEDB;SERVER=" 'this provider is needed to allow use of SP as form.recordset 
      ADOconnStr = ADOconnStr & rs("ServerName") & ";DATABASE=" & rs("DatabaseName") & ";UID=" 
      ADOconnStr = ADOconnStr & rs("dbUser") & ";PWD=" & EncryptDecrypt(Nz(rs("dbPassword"), "")) 
     End If 
     rs.Close 
     Set rs = Nothing 
     Set conn = Nothing 
    End If 
    getStrConn = ADOconnStr 
End Function 
Public Sub resetConnection() 
    ADOconnStr = "" 
    DAOconnStr = "" 
End Sub 
Function getStrConnDAO(Optional configID As Long = 0) As String 
    If DAOconnStr = "" Then 
     Dim a As New ADODB.Connection 
     a.Open getStrConn(configID) 
     DAOconnStr = "ODBC;driver=SQL Server;" & a.Properties("Extended Properties") & ";" 
     Set a = Nothing 
    End If 
    getStrConnDAO = DAOconnStr 
End Function 

그리고 마지막으로 데이터베이스 암호의 간단한 암호화 캐주얼 눈이 분명하지 수 있도록이 필요합니다

'//Name  : AttachTable 
    '//Purpose : Create a linked table to SQL Server without using a DSN 
    '//Parameters 
    '//  stLocalTableName: Name of the table that you are creating in the current database 
    '//  stRemoteTableName: Name of the table that you are linking to on the SQL Server database 
Private Function AttachTable(stLocalTableName As String, stRemoteTableName As String) 
    Dim td As TableDef 
    Dim stConnect As String 
    Me.messages = "Connecting to Database Table " & Me.mainDatabase & "." & stRemoteTableName 
    DoEvents 
    On Error Resume Next 
    CurrentDb.TableDefs.Delete stLocalTableName 
    If Err.Number <> 0 Then 
     If Err.Number <> 3265 Then GoTo AttachTable_Err 'v4.0.44 - allow delete errors 
     Err.Clear 
    End If 
    On Error GoTo AttachTable_Err 
    Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, getStrConnDAO(configID)) 
    CurrentDb.TableDefs.Append td 
    DoEvents 
    AttachTable = True 
    Exit Function 

AttachTable_Err: 

    AttachTable = False 
    errMsg = "AttachTable encountered an unexpected error: " & Err.description & " on table " & stRemoteTableName & " in database " & Me.mainDatabase 

End Function 

첨부 된 테이블 함수 - 뭔가 다시 인터넷에서 복사했습니다.

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
''' Comments: Performs XOr encryption/decryption on string data. Passing a 
'''    string through the procedure once encrypts it, passing it 
'''    through a second time decrypts it. 
''' 
''' Arguments: szData   [in|out] A string containing the data to 
'''        encrypt or decrypt. 
''' 
''' Date  Developer  Action 
''' -------------------------------------------------------------------------- 
''' 05/18/05 Rob Bovey  Created 
''' 
Public Function EncryptDecrypt(szData As String) As String 

    Const lKEY_VALUE As Long = 215 

    Dim bytData() As Byte 
    Dim lCount As Long 

    bytData = szData 

    For lCount = LBound(bytData) To UBound(bytData) 
     bytData(lCount) = bytData(lCount) Xor lKEY_VALUE 
    Next lCount 

    EncryptDecrypt = bytData 

End Function 
관련 문제