Access编程交流网
  • 设为首页|收藏本站|繁体中文|手机版
  •     
  • Access培训-Access开发平台-Access行业开发

  • 首页
  • 资讯
  • 技巧
  • 源码
  • 行业
  • 资源
  • 活动
  • 关于

技巧

ACCESS数据库

启动/设置/选项/背景

修复/压缩

安全/加密/解密

快捷键

版本升级/其它等

数据表

命名方式/设计规范

表设计

查询

Sql语言基础

选择查询

更新查询

删除查询

追加查询

生成表查询

交叉表查询

SQL特定查询

查询参数

查询综合应用

界面/窗体/控件

标签

文本框

命令按钮

组合框/列表框

选项组/复选框/选项按钮

选项卡

子窗体

窗体本身/综合应用

其它

报表打印

报表设计

高级报表

模块/函数/VBA/API/系统

VBA基础

内置函数

调试/跟踪/Debug

模块/类模块

API/COM/系统相关

字符数字日期

网络通信游戏

加密解密安全

文件处理

经典算法

宏/菜单/工具栏/功能区

宏/脚本

菜单/工具栏

功能区/Ribbon

图表/图形/图像/多媒体

图表

图形/图像

音频

视频/动画

DAO/链接表/ADO/ADP

DAO/链接表/ODBC

ADO/RDO

ADP

ActiveX/第三方控件/插件

Treeview树控件

ListView列表控件

Toolbar工具栏控件

微软其它控件

Dbi-Tech

CodeJock

Grid++Report

FastReport

ComponentOne

加载项/插件/Addin

OFFICE集成/导入导出/交互

Excel导入导出/交互

Word导入导出/交互

PPT交互

Outlook控制/邮件

Text文本文件/INI/CSV

PDF/SWF/XML格式

CAD格式

Sharepoint/其它Office

SqlServer/其它数据库

表

视图

存储过程/触发器

函数

用户/权限/安全

调试/维护

SqlServer其它/综合

发布/打包/文档/帮助

开发版/运行时

打包/发布/部署

开发文档/帮助制作

Access完整行业系统

采购管理系统

销售管理系统

仓库管理系统

人力资源管理HRM

CRM管理系统

MRP/ERP管理系统

BRP/流程优化

其它管理系统

心得/经验/绝招
其它/杂项
Excel技巧

Excel应用与操作

Excel开发编程

Word技巧

Word应用与操作

Word开发编程

Outlook技巧

Outlook应用与操作

Outlook开发编程

热门文章

  • vba的instr到sql..
  • SQL Server日期格..
  • Access几种注册ODB..
  • 如何导入有密码的MDB文件..
  • 返回存储过程OUTPUT参..
  • 处理加了密码的MDB文件

最新文章

  • 实验报告 --DAO与AD..
  • 用代码创建mdb格式的Ac..
  • 连接后台数据库提示 无法启..
  • 64位windows系统如..
  • Access的DAO准确获..
  • 利用代码自动创建ODBC源

联系方式

Access交流网(免费Access交流)

QQ:18449932 

网  址:www.access-cn.com

当前位置:首页 > 技巧 > DAO/链接表/ADO/ADP
DAO/链接表/ADO/ADP

使用代码刷新ODBC链接表

原文链接:http://www.mvps.org/access/tables/tbl0010.htm

Personally, I find the manual steps required to link to an ODBC table rather annoying.  If you feel the same way, here's how to automate the whole process.

    I'd suggest creating a table with three fields,

LocalTableName -- The name of the ODBC table as it appears in the Database window.

ConnectString -- The complete connect string to the ODBC Table. (Can be viewed by

?CurrentDB.TableDefs("SomeODBCTable").Connect

SourceTable -- The actual name of the ODBC table in the Data source. May be the same as Local Table Name.

Store this information for all ODBC tables in this table (referred to as tblReconnectODBC in code).  The benefit is that when this code is run in a new mdb, it re-creates a tabledef for each entry in this table if no ODBC Links are found in the database.

    If you want, you can also add RegisterDatabase method to this code when the DSNs are not found in registry. I, unfortunately, haven't had any luck with it since I'm dealing with Oracle.

'****************** Code Start *********************>
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Option Compare Database
Option Explicit

Private Type tODBCInfo
    strTableName As String
    strNewName As String
    strConnectString As String
    strSourceTable As String
End Type

'Contains all info for tables
Private mastODBCInfo() As tODBCInfo

'*** Registry stuff
Private Const HKEY_CLASSES_ROOT = &H80000000
Private Const HKEY_CURRENT_USER = &H80000001
Private Const HKEY_LOCAL_MACHINE = &H80000002
Private Const HKEY_USERS = &H80000003
Private Const HKEY_PERFORMANCE_DATA = &H80000004
Private Const HKEY_CURRENT_CONFIG = &H80000005
Private Const HKEY_DYN_DATA = &H80000006
Private Const STANDARD_RIGHTS_READ = &H20000
Private Const KEY_QUERY_VALUE = &H1&
Private Const KEY_ENUMERATE_SUB_KEYS = &H8&
Private Const KEY_NOTIFY = &H10&
Private Const Synchronize = &H100000
Private Const KEY_READ = ((STANDARD_RIGHTS_READ Or _
                        KEY_QUERY_VALUE Or _
                        KEY_ENUMERATE_SUB_KEYS Or _
                        KEY_NOTIFY) And _
                        (Not Synchronize))
Private Const MAXLEN = 256
Private Const ERROR_SUCCESS = &H0&
Const REG_NONE = 0
Const REG_SZ = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_DWORD_LITTLE_ENDIAN = 4
Const REG_DWORD_BIG_ENDIAN = 5
Const REG_LINK = 6
Const REG_MULTI_SZ = 7
Const REG_RESOURCE_LIST = 8

Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type

Private Declare Function apiRegOpenKeyEx Lib "advapi32.dll" _
        Alias "RegOpenKeyExA" _
        (ByVal hKey As Long, _
        ByVal lpSubKey As String, _
        ByVal ulOptions As Long, _
        ByVal samDesired As Long, _
        ByRef phkResult As Long) _
        As Long

Private Declare Function apiRegCloseKey Lib "advapi32.dll" _
        Alias "RegCloseKey" _
        (ByVal hKey As Long) _
        As Long

Private Declare Function apiRegQueryValueEx Lib "advapi32.dll" _
        Alias "RegQueryValueExA" _
        (ByVal hKey As Long, _
        ByVal lpValueName As String, _
        ByVal lpReserved As Long, _
        ByRef lpType As Long, _
        lpData As Any, _
        ByRef lpcbData As Long) _
        As Long

Private Declare Function apiRegQueryInfoKey Lib "advapi32.dll" _
        Alias "RegQueryInfoKeyA" _
        (ByVal hKey As Long, _
        ByVal lpClass As String, _
        ByRef lpcbClass As Long, _
        ByVal lpReserved As Long, _
        ByRef lpcSubKeys As Long, _
        ByRef lpcbMaxSubKeyLen As Long, _
        ByRef lpcbMaxClassLen As Long, _
        ByRef lpcValues As Long, _
        ByRef lpcbMaxValueNameLen As Long, _
        ByRef lpcbMaxValueLen As Long, _
        ByRef lpcbSecurityDescriptor As Long, _
        ByRef lpftLastWriteTime As FILETIME) _
        As Long



Function fReconnectODBC() As Boolean
Dim db As Database, tdf As TableDef
Dim varRet As Variant, rs As Recordset
Dim strConnect As String
Dim intTableCount As Integer
Dim i As Integer
Dim strTmp As String, strMsg As String
Dim boolTablesPresent As Boolean
Const cERR_NODSN = vbObjectError + 300
Const cREG_PATH = "Software\ODBC\ODBC.INI"

    On Error GoTo fReconnectODBC_Err

    'Check to make sure ODBC DSNs are present
    'You can follow the same steps to check for multiple DSNs
    strTmp = fReturnRegKeyValue(HKEY_CURRENT_USER, _
                        cREG_PATH & "\qc03", "Server")
    If strTmp = vbNullString Then Err.Raise cERR_NODSN

    'Another ODBC DSN
    strTmp = fReturnRegKeyValue(HKEY_CURRENT_USER, _
                        cREG_PATH & "\PMIP", "Server")
    If strTmp = vbNullString Then Err.Raise cERR_NODSN


    If MsgBox("Is it ok to drop ODBC links and reconnect?" _
                & vbCrLf & vbCrLf & _
                "The linked ODBC tables will be renamed " _
                & "and then reconnected. " _
                & vbCrLf & "If there were no errors encountered, " _
                & "then the old tables links will be deleted.", _
                vbQuestion + vbYesNo, _
                "Please confirm") = vbYes Then
        Set db = CurrentDb
        intTableCount = 0
        varRet = SysCmd(acSysCmdSetStatus, "Storing ODBC link info.....")

        Set rs = db.OpenRecordset("tblReconnectODBC", dbOpenSnapshot)

        boolTablesPresent = False
        For Each tdf In db.TableDefs
            strConnect = tdf.Connect
            If Len(strConnect) > 0 And left$(tdf.Name, 1) <> "~" Then
                If left$(strConnect, 4) = "ODBC" Then
                    ReDim Preserve mastODBCInfo(intTableCount)
                    With mastODBCInfo(intTableCount)
                        .strTableName = tdf.Name
                        rs.FindFirst "TableName='" & .strTableName & "'"
                        If Not rs.NoMatch Then
                            .strConnectString = rs!ConnectString
                            .strSourceTable = rs!SourceTable
                        Else
                            .strSourceTable = tdf!SourceTableName
                            .strConnectString = tdf!ConnectString
                        End If
                    End With
                    boolTablesPresent = True
                    intTableCount = intTableCount + 1
                End If
            End If
        Next

        'now attempt relink
        If Not boolTablesPresent Then
            'No ODBC Tables present yet
            'Reconnect from the table info
            strMsg = "No ODBC tables were found in this database." & vbCrLf _
                            & "Do you wish to reconnect to all the ODBC sources " _
                            & "listed in 'tblReconnectODBC' tables?"
            If MsgBox(strMsg, vbYesNo + vbQuestion, "ODBC Tables not present") = _
                            vbYes Then
                With rs
                    .MoveFirst
                    Do While Not .EOF
                        varRet = SysCmd(acSysCmdSetStatus, "Relinking '" _
                                            & !TableName & "'.....")
                        Set tdf = db.CreateTableDef(!TableName, _
                                            dbAttachSavePWD, _
                                            !SourceTable, _
                                            !ConnectString)
                        db.TableDefs.Append tdf
                        db.TableDefs.Refresh
                        .MoveNext
                    Loop
                End With
            End If
        Else
            For i = 0 To intTableCount - 1
                With mastODBCInfo(i)
                    varRet = SysCmd(acSysCmdSetStatus, "Attempting to relink '" _
                                        & .strTableName & "'.....")
                    strTmp = Format(Now(), "MMDDYY-hhmmss")
                    db.TableDefs(.strTableName).Name = .strTableName & strTmp
                    db.TableDefs.Refresh
                    .strNewName = .strTableName & strTmp
                    Set tdf = db.CreateTableDef(.strTableName, _
                                                                dbAttachSavePWD, _
                                                                .strSourceTable, _
                                                                .strConnectString)
                    db.TableDefs.Append tdf
                    db.TableDefs.Refresh
                    DoCmd.DeleteObject acTable, .strNewName
                End With
            Next
        End If
    End If
    varRet = SysCmd(acSysCmdClearStatus)
    fReconnectODBC = True
    MsgBox "All ODBC tables were successfully reconnected.", _
                    vbInformation + vbOKOnly, "Success"

fReconnectODBC_Exit:
    Set tdf = Nothing
    Set db = Nothing
    Erase mastODBCInfo
Exit Function
fReconnectODBC_Err:
    Dim errX As Error

    If Errors.Count > 1 Then
        For Each errX In Errors
            strMsg = strMsg & "Error #: " & errX.Number & vbCrLf & errX.Description
        Next
        MsgBox strMsg, vbOKOnly + vbExclamation, "ODBC Errors in reconnect"
    Else
        If Err.Number = cERR_NODSN Then
            MsgBox "The User DSN for Oracle Tables were not found. Please " _
                & "check ODBC32 under Control Panel.", vbExclamation + vbOKOnly, _
                "Couldn't locate User Data Sources"
        Else
            strMsg = "Error #: " & Err.Number & vbCrLf & Err.Description
            MsgBox strMsg, vbOKOnly + vbExclamation, "VBA Errors in reconnect"
        End If
    End If
    fReconnectODBC = False

    Resume fReconnectODBC_Exit
End Function


Function fReturnRegKeyValue(ByVal lngKeyToGet As Long, _
                            ByVal strKeyName As String, _
                            ByVal strValueName As String) _
                            As String

Dim lnghKey As Long
Dim strClassName As String
Dim lngClassLen As Long
Dim lngReserved As Long
Dim lngSubKeys As Long
Dim lngMaxSubKeyLen As Long
Dim lngMaxClassLen As Long
Dim lngValues As Long
Dim lngMaxValueNameLen As Long
Dim lngMaxValueLen As Long
Dim lngSecurity As Long
Dim ftLastWrite As FILETIME
Dim lngType As Long
Dim lngData As Long
Dim lngTmp As Long
Dim strRet As String
Dim varRet As Variant
Dim lngRet As Long
    On Error GoTo fReturnRegKeyValue_Err
    'Open the key first
    lngTmp = apiRegOpenKeyEx(lngKeyToGet, _
                strKeyName, 0&, KEY_READ, lnghKey)

    'Are we ok?
    If Not (lngTmp = ERROR_SUCCESS) Then Err.Raise lngTmp + vbObjectError

    lngReserved = 0&
    strClassName = String$(MAXLEN, 0):  lngClassLen = MAXLEN
    'Get boundary values
    lngTmp = apiRegQueryInfoKey(lnghKey, strClassName, _
        lngClassLen, lngReserved, lngSubKeys, lngMaxSubKeyLen, _
        lngMaxClassLen, lngValues, lngMaxValueNameLen, _
        lngMaxValueLen, lngSecurity, ftLastWrite)

    'How we doin?
    If Not (lngTmp = ERROR_SUCCESS) Then Err.Raise lngTmp + vbObjectError

    'Now grab the value for the key
    strRet = String$(MAXLEN - 1, 0)
    lngTmp = apiRegQueryValueEx(lnghKey, strValueName, _
                lngReserved, lngType, ByVal strRet, lngData)
    Select Case lngType
        Case REG_SZ
            lngTmp = apiRegQueryValueEx(lnghKey, strValueName, _
                lngReserved, lngType, ByVal strRet, lngData)
            varRet = left(strRet, lngData - 1)
        Case REG_DWORD
            lngTmp = apiRegQueryValueEx(lnghKey, strValueName, _
                lngReserved, lngType, lngRet, lngData)
            varRet = lngRet
        Case REG_BINARY
            lngTmp = apiRegQueryValueEx(lnghKey, strValueName, _
                lngReserved, lngType, ByVal strRet, lngData)
            varRet = left(strRet, lngData)
    End Select

    'All quiet on the western front?
    If Not (lngTmp = ERROR_SUCCESS) Then Err.Raise lngTmp + vbObjectError

fReturnRegKeyValue_Exit:
    fReturnRegKeyValue = varRet
    lngTmp = apiRegCloseKey(lnghKey)
    Exit Function
fReturnRegKeyValue_Err:
    varRet = vbNullString
    Resume fReturnRegKeyValue_Exit
End Function
'****************** Code End *********************
发布人:Dev Ashi…-http://www.mvps.org/access/  
分享到:
点击次数:  更新时间:2005-02-04 13:15:44  【打印此页】  【关闭】
上一条:如何隐藏/显示某个表或者其他数据库对象  下一条:Excel制作奖金计算表 算出员工工资



相关文章

  • • 实验报告 --DAO与ADO效率之比较
  • • 用代码创建mdb格式的Access文件
  • • 连接后台数据库提示 无法启动应用程序。工作组信息文件丢失,或是已被其它用户以独占方式打开 的解决办法
  • • 64位windows系统如何使用64位的ADO连接Accesss accdb数据库(ACE.OLEDB)
  • • Access的DAO准确获取记录集Recordset的记录数Recordcount
  • • 利用代码自动创建ODBC源
  • • 在打开Ado记录集之前尽量先判断记录集有否打开,如打开则先关闭之
  • • 快速获取Excel文件所有工作表表名

热门文章

  • [2004-04-02] [分享]使用代码刷新ODBC链接SQL SEVER表access数据库
  • [2006-11-20] ADO连接数据库字符串大全access数据库
  • [2005-02-18] SQL语句集锦4access数据库
  • [2004-11-23] 一句代码得到SQL SERVER时间的函数access数据库
  • [2003-12-20] sqlserver2000数据库规格access数据库
  • [2005-01-08] SQL Server日期格式的转换access数据库

热门产品

公司动态|在线留言|在线反馈|友情链接|会员中心|站内搜索|网站地图

中山市天鸣科技发展有限公司 版权所有 1999-2023 粤ICP备10043721号

QQ:18449932

Access应用 Access培训 Access开发 Access平台

access|数据库|access下载|access教程|access视频|access软件

Powered by MetInfo 5.3.12 ©2008-2025  www.metinfo.cn