简体   繁体   English

如何通过VB建立与MySQL的连接并在表单上显示简单的查询结果?

[英]How do I establish a connection to MySQL via VB & display simple query results on a form?

I have a project in Visual Studio 2008 and there is a working data connection to a MySQL database. 我在Visual Studio 2008中有一个项目,并且到MySQL数据库的数据连接正常。 In other words, I can query the db directly from Visual Studio and it will display the results. 换句话说,我可以直接从Visual Studio查询数据库,它将显示结果。

I've tried a couple of approaches that I found online for writing a connection string and accessing the db, but no luck yet. 我尝试了几种在线找到的方法,这些方法用于编写连接字符串和访问数据库,但还算不上成功。

All I'm trying to do is code a button to query the db and then reset the text property of a label/textbox to display the results based upon another label/textbox value. 我要做的就是编写一个查询数据库的按钮的代码,然后重置标签/文本框的text属性以根据另一个标签/文本框值显示结果。

The pseudo-code I am imagining is something like this: 我想象中的伪代码是这样的:

    Private Sub query_submit_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles query_submit_button.Click
        result_textbox.Text = SELECT field FROM table WHERE otherfield = key_textbox.Text
    End Sub

I didn't see any related questions posted on SO - forgive me if I missed one that already exists and this is a dupe. 我没有在SO上看到任何相关的问题-如果我错过了一个已经存在的问题,请原谅我,这是骗子。

What is the correct way to accomplish this? 什么是实现此目的的正确方法?


EDIT 编辑
Using MySQL 5.1 使用MySQL 5.1

You can download the ODBC Provider and then reference, import, and use it to query the database through a ODBCCommand instance. 您可以下载ODBC提供程序 ,然后引用,导入并使用它通过ODBCCommand实例查询数据库。

'Put this at the very top of your .VB file...
Imports System.Data.ODBC

'Put this in some method in your code when you are ready to query the DB...
Using connection As New OdbcConnection(connectionString)
    Dim command As New OdbcCommand(strSqlQuery, connection)
    connection.Open()
    result_textbox.Text = command.ExecuteScalar.ToString
End Using

i used DaMartyr's answer to get 99% there, but needed to add this declaration: 我使用DaMartyr的答案获得了99%的答案,但需要添加以下声明:

Dim connectionString As String = "driver={MySQL ODBC 5.1 Driver};server=SERVER;uid=USERID;pwd=PASSWORD;database=DATABASE"

just replace the SERVER , USERID , PASSWORD , & DATABASE with your personal settings 只需将SERVERUSERIDPASSWORDDATABASE替换为您的个人设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM