Visual Basic 6.0的MySQL示例 - 读/写

5

我希望能找到一个关于使用远程MySQL数据库的简单示例。我知道互联网上有一些教程,解释如何设置ADODB.Connection和connectionstrings,但是我无法使其正常工作。感谢任何帮助!

1个回答

7

MySQL下载页面下载ODBC连接器

这里查找正确的connectionstring

在您的VB6项目中选择对Microsoft ActiveX Data Objects 2.8 Library的引用。如果您使用的是Windows Vista或Windows 7,则可能还有一个6.0库。如果您希望您的程序也能在Windows XP客户端上运行,那么最好使用2.8库。如果您的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

谢谢,但是每次我尝试连接时它都会返回“无法连接到mysql服务器...” 我已经检查了服务器、用户名和密码 - 一切都是正确的。 - f1nn
顺便说一句,我肯定使用了用于远程访问的连接字符串。 - f1nn
这是完整的错误截图:http://tinyurl.com/mysqlerror-12您可以尝试自己连接,这是我使用的连接字符串:Driver={MySQL ODBC 5.1 Driver};Server=mysql.mtgrand.z8.ru;Database=db_mtgrand_2;User=dbu_mtgrand_2;Password=nvt8ZzjD5tZ;Option=3;它不是私有的,所以您可以尝试登录。现在数据库没有表,它是空的,但即使是空的,它也应该至少连接。 - f1nn
1
添加了第一个表格“客户”,其中包含1个字段“ID”。 - f1nn
我甚至无法ping通你的服务器。在我看来,这更像是一个网络相关的问题。尝试自己ping一下主机名,看看结果如何。如果你可以ping通,那么尝试使用MySQL Workbench或其他MySQL客户端软件连接服务器。如果它们无法连接,那么你的VB6代码也无法连接。 - Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接