将ADO记录集打开为可见表

时间:2017-05-02 16:13:30

标签: mysql access-vba odbc ado

我第一次做这样的事情,看起来很难找到任何有用的信息。

我想做什么: 将select-query传递给MySQL数据库并在表中显示结果。

我现在已经有了这么远:我在表单上有一个按钮,当点击时会发生以下情况

Option Compare Database

Sub RunPassThrough(strSQL As String)

Dim ConnectionString As String
Dim Server As String
Dim User As String
Dim Pwd As String
Dim DatabaseName As String
Dim Cn As ADODB.Connection
Dim Rs As ADODB.Recordset


' Server Hostname (or IP)
Server = "192.168.178.10"

User = "user"
Pwd = "mypass"

DatabaseName = "myDB"

ConnectionString = "Provider=MSDASQL;Driver={MYSQL ODBC 5.1 DRIVER};" & _
        "Server=" & Server & ";Database=" & DatabaseName

Set Cn = New ADODB.Connection
Cn.CursorLocation = adUseClient
Cn.Mode = adModeShareDenyNone
Cn.Open ConnectionString, User, Pwd

Set Rs = New ADODB.Recordset


Rs.Open strSQL, Cn, adOpenDynamic, adLockReadOnly
'Set Rs = Cn.Execute("select * from SurveyResults limit 10;")





End Sub

Private Sub Befehl0_Click()

Dim SQL As String

SQL = "select * from SurveyResults limit 10;"

RunPassThrough (SQL)


End Sub

我知道Rs.Open strSQL, Cn, adOpenDynamic, adLockReadOnly会返回一个ADO记录集,我可以使用VBA来处理它,但我想要的只是在表中显示该记录设置给用户。

类似OpenRecordset(“Rs”,用户可以看到的表)

有人可以指出我正确的方向我疯了......

1 个答案:

答案 0 :(得分:1)

我明白了。我的问题很简单,默认情况下,ReturnsRecords属性设置为false。

它现在有效,所以如果有人需要,我会发布答案。

Sub RunPassThrough(strSQL As String)

Dim Server As String
Dim User As String
Dim Pwd As String
Dim DatabaseName As String
Dim qdfPassThrough As DAO.QueryDef, MyDB As Database
Dim strConnect As String


' Server Hostname (or IP)
Server = "192.168.178.10"

User = "user"
Pwd = "mypass"

DatabaseName = "database"



For Each qdf In CurrentDb.QueryDefs
If qdf.Name = "PassQuery" Then
    CurrentDb.QueryDefs.Delete "PassQuery"
    Exit For
End If
Next

    strConnect = "ODBC;DRIVER={MYSQL ODBC 5.1 DRIVER};SERVER=" & Server & ";DATABASE=" & DatabaseName & ";Uid=" & User & ";Pwd=" & Pwd & ";"

    Set MyDB = CurrentDb()

    Set qdfPassThrough = MyDB.CreateQueryDef("PassQuery")


    qdfPassThrough.Connect = strConnect
    qdfPassThrough.SQL = strSQL
    qdfPassThrough.Close

    Application.RefreshDatabaseWindow
    MyDB.QueryDefs("PassQuery").ReturnsRecords = True

    DoCmd.OpenQuery "PassQuery", acViewNormal, acReadOnly
    DoCmd.Maximize


End Sub