Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ADO.NET & Database » Accessing MySQL Database in VB.NET

Accessing MySQL Database in VB.NET

In this article, I will show you how to access MySQL server database using ODBC data provider. There are two ways to access MySQL Server database using ODBC data providers. First, using ODBC data source name and second by passing connection string direct in the OdbcConnection object.

Author Rank :
Page Views : 150589
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Mindcracker MVP Summit 2012
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In this article, I will show you how to access MySQL server database using ODBC data provider. There are two ways to access MySQL Server database using ODBC data providers. First, using ODBC data source name and second by passing connection string direct in the OdbcConnection object.

Using MySQL Database

As I've been saying, working with different data sources is only a matter of changing the connection string. You can access a MySQL database either using a DSN or using the  direct database name in the connection string. You can use a database name directly as shown in the following code:

Dim connectionString As String = "Driver={MySQL};SERVER=localhost;DATABASE=NorthwindMySQL;"

Or you can use an ODBC DSN, as you can see from the following code that I've used TestDSN DSN to connect to the data source:    

Dim conn As New OdbcConnection("DSN=TestDSN")

To test this code, create a Windows application and add a DataGrid control to the form and write code listed in Listing 1 on the form load. As you can see in Listing this code is similar to the code you saw earlier. It creates a connection, a data adapter, fills the dataset from the data adapter, and sets the dataset's DefaultViewManager as the DataGrid control's DataSource property.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim connectionString As String = "Driver={MySQL};SERVER=localhost;DATABASE=NorthwindMySQL;" '
Dim conn As New OdbcConnection(connectionString)
conn.Open()
Dim da As New OdbcDataAdapter("SELECT CustomerID, ContactName, ContactTitle FROM Customers", conn)
Dim ds As New DataSet("Cust")
da.Fill(ds, "Customers")
dataGrid1.DataSource = ds.DefaultViewManager
conn.Close()
End Sub 'Form1_Load

Listing 1. Accessing a MySQL database

Note:

In this code, I have converted Northwind Access database to MySQL database. You make sure you replace your database name, table, user ID and password.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
where is the Listing 11-12 by rolin On March 2, 2006

hi there...

u mentioned in ur article : "To test this code, create a Windows application and add a DataGrid control to the form and write code listed in Listing 11-2 on the form load."

but i can only see Listing 1. so where can i find the Lingting 11 and 12?

thank you...

Reply | Email | Modify 
Re: where is the Listing 11-12 by Mahesh On September 28, 2007
It supposed to be Listing1. I fixed it. Thanks.
Reply | Email | Modify 
how about...? by jhae On September 27, 2007
how about... ADo.net and msql in to VB2005? & ADO.net and/or msql in to VCpp.net
Reply | Email | Modify 
ado.net by srivatsan On October 29, 2007
the article is useful.....
Reply | Email | Modify 
thanks by kyoshiro On November 19, 2007
this article really is reliable. thanks !
Reply | Email | Modify 
OdbcConnection not define by nell On December 14, 2007
i was trying your code in listing 1 and i have this error on my vb.net code OdbcConnection not define what seems to be the problem?
Reply | Email | Modify 
Question by mehrdad On January 28, 2008
hi mahesh I'm mehrdad from Iran Please tell me a reference for VB.net Database Sql server 2005 and asp.net thak you
Reply | Email | Modify 
Re: Question by Mahesh On April 7, 2009
Click on ADO.NET link in the left side bar on the home page of this site. ADO.NET section has many articles on database accessing using ADO.NET and VB.NET. Post your questions on the forums if you can't find your answer.
Reply | Email | Modify 
give a idea by samiullah On February 9, 2008
Dear Sir my name is samiullah im student of computer science in afhanistan. Dear sir i know some basic thing about vb.net and i have developed some small databases like for shops and schools. dear sir i wanna to learn vb.net more here in afghanistan are not smart teachers that i learn something new,if you dont mind would you please send some lecture that i learn something from your notes i wil be very glad best regard samiullah
Reply | Email | Modify 
Re: give a idea by Mahesh On April 7, 2009
This site and C# Corner are all filled with lot of tutorials and articles. Start with beginner section at the top and post your questions on the forums.
Reply | Email | Modify 
give a idea2 by samiullah On February 9, 2008
dear sir i forgot something to tell you that im make connectiveties with sqlserver2000 toward that send me lectures please sir bye
Reply | Email | Modify 
conneccting to an access database using ADO.net by Damion On August 17, 2008
Mahesh, I notice that the codes for connecting to an access database are not as they were with VB6. I am trying to connect to an access database in ado.net. How is that done? That was a good article by the way!
Reply | Email | Modify 
Re: conneccting to an access database using ADO.net by Mahesh On April 7, 2009
Here is an article in C#. Conversion to VB.NET should be pretty straight forward:
http://www.c-sharpcorner.com/UploadFile/mimrantaj/Database102102008130743PM/Database1.aspx
Reply | Email | Modify 
Any idea how to use the Chart forms and Mysql in VB .Net 2008-Express? by Arnaud On February 15, 2010
Hi,
Any idea how to use the Chart forms and Mysql in VB .Net 2008-Express?
I’m referring to this library:
http://code.msdn.microsoft.com/mschart
I’m having trouble to bind the chart to my data, would be great if you can help


Here is my code writen in the form containing the chart form:
————————————————
Imports MySql.Data.MySqlClient
Imports MySql.Data
Imports System.Data

Public Class frmIVvsRLZ
Private Sub cmdChart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdChart.Click
Dim rdr As MySqlDataReader
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL1 As String

conn.ConnectionString = My.Settings.connectionString

SQL1 = “SELECT CLOSINGDATE, HISTO10D FROM TBLHISTOVOLBBG WHERE EQUITY_ID=1845 ORDER BY CLOSINGDATE DESC”

Try
conn.Open()

Try

cmd.CommandText = SQL1
cmd.Connection = conn
rdr = cmd.ExecuteReader

chartHistoIVvsRLZ.DataSource = rdr

chartHistoIVvsRLZ.DataBind()

Catch myerror As MySqlException
MsgBox(“There was an error reading from the database: ” & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show(“Error connecting to the database: ” & myerror.Message)
Finally
If conn.State ConnectionState.Closed Then conn.Close()
End Try
End Sub

End Class

--------------------------------

As well I teid this


------------------------------------------


Imports MySql.Data.MySqlClient
Imports MySql.Data
Imports System.Data
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim query As String = “SELECT CLOSINGDATE, HISTO10D FROM TBLHISTOVOLBBG WHERE EQUITY_ID=1845 ORDER BY CLOSINGDATE DESC”
Dim connection As New MySqlConnection(My.Settings.connectionString)
Dim da As New MySqlDataAdapter(query, connection)
Dim ds As New DataSet()

If da.Fill(ds) Then
Chart1.DataSource = ds.Tables(0)
Chart1.DataBind()
End If
connection.Close()

Catch ex As Exception
Console.WriteLine(ex.Message)

End Try
End Sub
End Class


Reply | Email | Modify 
Database connection by Thobisa On April 16, 2010

Can you explain this code please.

Dim connectionString As String = "Driver={MySQL};SERVER=localhost;DATABASE=NorthwindMySQL;" '
Dim conn As New OdbcConnection(connectionString)
conn.Open()

Reply | Email | Modify 
Inserting Record by winlove On June 26, 2010
I have this code, and whenever i try it to RUN, I always get an error and it's like this........

ODBCEXCEPTION WAS UNHANDLED
ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.51b-community-nt]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'char VALUES('101','noodles')' at line 1


How can i solve this..? below is my complete codes.... and by the way i can't see
MySql Odbc in my data source and if i try to add data source mysql doesn't appear..
I'm using VB2008 express edition... tnx

--------------------------------------------------------------------------------------------------------------------

'Imports System.ServiceProcess
Imports System
Imports Microsoft.Data.Odbc
Imports System.Data.SqlClient
Imports System.Data.SqlClient.SqlCommand
Imports MySql.Data.MySqlClient
Imports MySql.Data
Imports System.Data


Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load



     


        Dim MyConString As String = "DRIVER={MySQL ODBC 5.1 Driver};" & _
                                    "SERVER=localhost;" & _
                                    "DATABASE=char;" & _
                                    "UID=root;" & _
                                    "PASSWORD=;" & _
                                    "OPTION=0;"
        Dim da As New OdbcDataAdapter

        Dim MyConnection As New OdbcConnection(MyConString)

        Dim MyCommand As New OdbcCommand

        MyConnection.Open()

        MyCommand.Connection = MyConnection
        MyCommand.CommandText = ("INSERT INTO char VALUES('101','1002')")
    
        MyCommand.ExecuteNonQuery()
     

        MyConnection.Close()
        MyConnection.Dispose()
        MyCommand.Dispose()

    End Sub
End Class
Reply | Email | Modify 
anyone knows how to use ReportDocument and CrystalReportViewer by cris dennis On August 25, 2010
i hav vb.net 2005 and MySql as my database..
if anyone could share there code and sample appilcation on how to create a report Pls send me At tisoygyudko@yahoo.com
Or post it in here..

thanks..
Reply | Email | Modify 
How to fetch time field values from mysql database through vb.net code by Noah On April 1, 2011
Hi Mahesh Sir, i need help urgently on this please. “how to fetch time field values from mysql database through vb.net code??” i need to get those values and calculate running time for the day. +————-+————–+——+—–+————+——-+ here is the piece of code im currently working on. +————-+————–+——+—–+————+——-+ strQuery = “select IMEI,Pos_Date,Pos_Time,CountryCode,NetC,LAC,Cellid,SigStr,BattStr,Fuel_Level,ign,AI1,AI2,AI3,DI1,DG2,DG3,status from gensetfuel where imei=’” & imei & “‘ and Pos_Date=’” & dateSelected & “‘ Order by Pos_Time” +————-+————–+——+—–+————+——-+ sqlcomm = New MySqlCommand(strQuery, sqlcon) sqlreader = sqlcomm.ExecuteReader sqlcomm = New MySqlCommand(strQuery, sqlcon) sqlreader = sqlcomm.ExecuteReader +————-+————–+——+—–+————+——-+ If sqlreader.HasRows Then While sqlreader.Read() +————-+————–+——+—–+————+——-+ posDate = sqlreader.GetDateTime(1).ToString(“dd-MMM-yy”) If (firstreading) Then prevtime = sqlreader.GetDateTime(2) prevMovtime = prevtime firstreading = False End If +————-+————–+——+—–+————+——-+ time = sqlreader.GetDateTime(2) ignstate = sqlreader.GetValue(17) TimeDuration = DateDiff(DateInterval.Minute, prevtime, time) If TimeDuration > 10 Then ‘some code…. +————-+————–+——+—–+————+——-+ +————-+————–+——+—–+————+——-+ the values i am getttin for time and prevtime variables in vb.net code is 12:00:00AM and when i use datediff function i get the result as 0 database description of the table used is as: +————-+————–+——+—–+————+——-+ | Field | Type | Null | Key | Default | Extra | +————-+————–+——+—–+————+——-+ | IMEI | varchar(100) | NO | PRI | | | | Pos_Date | date | NO | PRI | 0000-00-00 | | | Pos_Time | time | NO | PRI | 00:00:00 | | | CountryCode | varchar(100) | YES | | NULL | | | NetC | varchar(100) | YES | | NULL | | | LAC | varchar(100) | YES | | NULL | | | Cellid | varchar(100) | YES | | NULL | | | SigStr | varchar(100) | YES | | NULL | | | BattStr | varchar(100) | YES | | NULL | | | Fuel_Level | varchar(100) | YES | | NULL | | | ign | varchar(100) | YES | | NULL | | | AI1 | varchar(100) | YES | | NULL | | | AI2 | varchar(100) | YES | | NULL | | | AI3 | varchar(100) | YES | | NULL | | | DI1 | varchar(100) | YES | | NULL | | | DG2 | varchar(100) | YES | | NULL | | | DG3 | varchar(100) | YES | | NULL | | | ser_inp | varchar(100) | YES | | NULL | | | status | varchar(100) | YES | | NULL | | +————-+————–+——+—–+————+——-+ +————-+————–+——+—–+————+——-+ the query mention above in the comment, strQuery=”select….” fetches me the correct set of records when fired on mysql command line client….........but its not giving the correct result through vb.net code…............. please help asap…............... thanks a tons in advance…...........vl b really obliged :o)
Reply | Email | Modify 
How to connect vb.net to wampserver? by badin On July 25, 2011
Hi, I want to use wampserver as our database for vb.net. Our project is all about library system. How can I do this? Can someone help me to do this for me. Thanks. Best Regards, jenie aranas
Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.