Programming Tutorials

How To Connect To A MySql Database in

By: Syed M Hussain in Tutorials on 2009-01-18  

To connect to a MySQL database in VB.NET, you can use the MySQL Connector/NET data provider. Here's a sample code that demonstrates how to establish a connection and execute a simple query:

Imports MySql.Data.MySqlClient

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' Connection string
        Dim connString As String = "server=localhost;user id=root;password=your_password;database=your_database"

        ' Create a MySqlConnection object
        Using conn As New MySqlConnection(connString)
            ' Open the connection

            ' Create a MySqlCommand object
            Dim cmd As New MySqlCommand("SELECT * FROM your_table", conn)

            ' Execute the query and get a MySqlDataReader object
            Using reader As MySqlDataReader = cmd.ExecuteReader()
                ' Loop through the result set
                While reader.Read()
                    ' Access the columns by name or index
                    Dim id As Integer = reader.GetInt32(0)
                    Dim name As String = reader.GetString(1)

                    ' Do something with the data
                    Console.WriteLine(id & " " & name)
                End While
            End Using
        End Using
    End Sub
End Class

In this code, you need to replace the connection string with your own MySQL server credentials and database name. After that, you can create a MySqlConnection object, open the connection, create a MySqlCommand object with your query, execute the query, and loop through the result set using a MySqlDataReader object.

Note that you need to install the MySQL Connector/NET data provider in order to use it in your VB.NET application. You can download it from the official MySQL website.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in )

Latest Articles (in