Using MySQL database in .Net

Last year i had to choose a Database Server for a new application i had to develop for my customer. The options was Access, SQL Server, Oracle. As you can imagine i decided to exclude Access from the list due to it’s slow performances. I had to decide between SQL Server and Oracle but, considering my customer budget, i decided to add to the list another database server, MySQL. I think that MySQL is a very interesting option when u have to save money for your projects, it’s cheap and fast enough to compete with SQL Server and Oracle.
To use a MySQL database you need to download the MyODBC 3.51 or better driver. I use 3.51 because it’s more stable. So to go on with the test please download MyODBC and install it before testing. Obviously you need MySQL and a database too.

Here is the simple code to access a MySQL database from VB.Net using MyODBC.
In this test we’ll connect to a MySQL database and read all the records of a table then we display one field in a web page.
In a desktop application you can use it the same way but remove the Response.write and use something else.

Dim SQL As String
Dim ConnString as string
 
ConnString= "DRIVER={MySQL ODBC 3.51 Driver};_
    SERVER=localhost;DATABASE=DatabaseName;_
    UID=UserID;PWD=thePassword;OPTION=35"

Dim Conn As New System.Data.Odbc.OdbcConnection(_
     _ConnString)
 
SQL = "SELECT * FROM TableName"
Conn.Open()
 
Dim Cmd As New System.Data.Odbc.OdbcCommand(SQL, Conn)
Cmd.CommandTimeout = 20
 
Dim Reader As System.Data.Odbc.OdbcDataReader
Reader = Cmd.ExecuteReader()
 
While (Reader.Read)
        Response.Write(Reader("FieldName") + "<br>")
End While
 
Reader.Close()
Cmd.Dispose()
Conn.Close()
Conn.Dispose()

Download this code: MySQLVB.vb.txt

That’s all :) really simple


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

1 Comment so far »

  1. Ed Bowles said

    am January 12 2007 @ 4:07 pm

    I tried this code and it worked first time. It saved me hours. Thanks

Comment RSS · TrackBack URI

Leave a comment

Name:

eMail:

Website:

Comment: