Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
 Resources  
Close
 Our Network  
Close
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:
Total page views :  107809
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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.


Login to add your contents and source code to this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
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 | Delete | 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 | Delete | 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 | Delete | Modify | 
ado.net by srivatsan On October 29, 2007
the article is useful.....
Reply | Email | Delete | Modify | 
thanks by kyoshiro On November 19, 2007
this article really is reliable. thanks !
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.