Thursday, February 2, 2012

Connecting Visual Basic 2010 with MySql database Cont...

Today We are going to learn that, How to write code in VB 2010 for connect to MySql Database

1. Open up new Visual Studio Project and create a form

2. Right Click on the form you create, and choose view code option

3. In the window you have shown, Type the code below

Imports MySql.Data.MySqlClient

the above line should be appear in the very top of the window that is, The above line should be type above public class formname

After that type the below code after the class declaration, That is after the line
public class formname


Dim ServerString As String = "Server=localhost;User Id=root;Password=pass;Database=dtbname"
Dim SQLConnection As MySqlConnection = New MySqlConnection

The above code line I use my server as localhost and user id as root password for the root is pass and the database is dtbname. You can use your own database details instead of the above

The second line of above code should be typed like what I have entered but you can change only the variable name SQLConnection to your own variable name

After that type the code below


SQLConnection.ConnectionString = ServerString


        Try
            If SQLConnection.State = ConnectionState.Closed Then
                SQLConnection.Open()
            Else
                SQLConnection.Close()
                MsgBox("Connection is closed")
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

Thats it you have connected to MySql database from Visual Basic 2010

Tomorrow we will show how to retrieve data from MySql table....

2 comments:

  1. I really like your blog coz it helped me when I was searching on how I can use mysql from WAMP with Visual Basic 2010. Even though am of little or no help but I wanted you to help me another task because am completely new with database and visual bsic and it is giving me some headaches.
    How to create database forms from your data in Visual basic?

    ReplyDelete