在没有持久数据库连接的情况下填充RowSource和RecordSource

时间:2018-08-21 09:25:57

标签: sql ms-access access-vba

正如标题所示,我想知道是否可以在不保持与我正在查询的外部数据库的持久连接的情况下填充RecordSource或RowSource。

我尝试了以下两种方法,但无济于事:

  

IN条款

ps.RecordSource = " SELECT TM_Adjudicator AS Adjudicator, Nz(Sum(PS_DB_view.PS_Points+PS_DB_view.PS_Adhoc),0) AS [Total Points] " & _
                      " FROM SD_Adjudicators_view " & _
                      " LEFT JOIN PS_DB_view ON (((cstr(SD_Adjudicators_view.TM_Adjudicator) = cstr(PS_DB_view.PS_Adjudicator)) AND cdate(PS_DB_view.PS_Date) >= #" & dtStart_fmt & "#) AND cdate(PS_DB_view.PS_Date) <= #" & dtEnd_fmt & "#) " & _
                      " IN '' [MS Access;PWD=**STRING**;DATABASE=I:\**PATH**\PM_DB_view.accdb] " & _
                      " WHERE SD_Adjudicators_view.TM_TeamName = 'Z999' " & _
                      " GROUP BY TM_Adjudicator; "

(这将在用户表单的生命周期内保持持久连接

  

DB.Connection

Set dbs = OpenDatabase("I:\**PATH**\PM_DB_testenvironment.accdb", False, False, "MS Access;**STRING**")
Set rst = dbs.OpenRecordset(" SELECT TM_Adjudicator AS Adjudicator, Nz(Sum(PS_DB_view.PS_Points+PS_DB_view.PS_Adhoc),0) AS [Total Points] " & _
                                                                " FROM SD_Adjudicators_view " & _
                                                                " LEFT JOIN PS_DB_view ON (((cstr(SD_Adjudicators_view.TM_Adjudicator) = cstr(PS_DB_view.PS_Adjudicator)) AND cdate(PS_DB_view.PS_Date) >= #" & dtStart_fmt & "#) AND cdate(PS_DB_view.PS_Date) <= #" & dtEnd_fmt & "#) " & _
                                                                " WHERE SD_Adjudicators_view.TM_TeamName = 'Z999' " & _
                                                                " GROUP BY TM_Adjudicator; ")

    Set ps.Form.RecordSource = rst

    rst.Close
    Set rst = Nothing

    dbs.Close
    Set dbs = Nothing

这也将保持持久的连接,直到调用close函数,并且RowSource / RecordSource的值都将丢失。

总有没有要读取数据,显示数据并关闭数据库,同时保持记录可见?

1 个答案:

答案 0 :(得分:2)

是的,有。

您可以使用ADODB断开记录集作为记录源。

代码:

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=I:\**PATH**\PM_DB_testenvironment.accdb;Jet OLEDB:Database Password=""**STRING**"""
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.CursorLocation = 3 'adUseClient
rs.Open "SELECT stuff FROM Table", conn, 3, 3 'adOpenStatic, adLockReadOnly
Set Me.Recordset = rs
conn.Close
Set rs.ActiveConnection = Nothing
Set conn = Nothing

请注意,除非您首先重新建立数据库连接,否则许多功能(例如排序和过滤)将无法使用。

很遗憾,DAO没有提供此功能。