5

我想找到一个使用远程 MySQL 库的简单示例。我知道,互联网上有一些教程,解释了如何设置 ADODB.Connection 和 connectionstrings,但我无法让它工作。谢谢你的帮助!

4

1 回答 1

7

ODBC connectorMySQL 下载页面下载。

connectionstring这里寻找右边。

在您的 VB6 项目中选择对Microsoft ActiveX Data Objects 2.8 Library. 如果您有 Windows Vista 或 Windows 7,那么您也可能有 6.0 库。如果您希望程序也可以在 Windows XP 客户端上运行,那么最好使用 2.8 库。如果您使用带有 SP 1 的 Windows 7,那么由于 SP1 中的兼容性错误,您的程序将永远不会在任何其他规格较低的系统上运行。您可以在KB2517589中阅读有关此错误的更多信息。

此代码应为您提供足够的信息来开始使用 ODBC 连接器。

Private Sub RunQuery()
    Dim DBCon As adodb.connection
    Dim Cmd As adodb.Command
    Dim Rs As adodb.recordset
    Dim strName As String

    'Create a connection to the database
    Set DBCon = New adodb.connection
    DBCon.CursorLocation = adUseClient
    'This is a connectionstring to a local MySQL server
    DBCon.Open "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase; User=myUsername;Password=myPassword;Option=3;"

    'Create a new command that will execute the query
    Set Cmd = New adodb.Command
    Cmd.ActiveConnection = DBCon
    Cmd.CommandType = adCmdText
    'This is your actual MySQL query
    Cmd.CommandText = "SELECT Name from Customer WHERE ID = 1"

    'Executes the query-command and puts the result into Rs (recordset)
    Set Rs = Cmd.Execute

    'Loop through the results of your recordset until there are no more records
    Do While Not Rs.eof
        'Put the value of field 'Name' into string variable 'Name'
        strName = Rs("Name")

        'Move to the next record in your resultset
        Rs.MoveNext
    Loop

    'Close your database connection
    DBCon.Close

    'Delete all references
    Set Rs = Nothing
    Set Cmd = Nothing
    Set DBCon = Nothing
End Sub
于 2012-04-05T08:09:04.283 回答