Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » ADO.NET & Database » Connect to MySQL database via ODBC using a DSN: Part I

Connect to MySQL database via ODBC using a DSN: Part I

This article shows how to connect with MySQL database via ODBC.

Author Rank :
Page Views : 30443
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   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
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Certainly if you ask me which one is better: Using Microsoft SQL server or MySQL server as a database to store your application data, I say, of course, Microsoft SQL server as it offers more features and demonstrates less number of bugs and problems. But what if the majority of hosting servers provides MySQL server as database system and even the minority that offers Microsoft SQL server is very expensive. Hence you haven't any choice but storing and manipulating your data from a MySQL database.   

In the below table, I try to compare the two products:

Characteristics  Microsoft SQL server MySQL server
Disponibility in the market according to my region (Tunisia) Less offered by the hosting server machines as they almost use Linux and Unix platforms , moreover, even if they make use of windows server platform MySQL server is more present than Microsoft SQL server It is rare to find a hosting server machine that offers Microsoft SQL server as a front end database, and even if you find one, it is more expensive than the equivalent that offers MySQL server
Features Offers less features Offers more features
Coherence with .Net application Less compatibility and more bugs in spite of the endeavors made to make easy the connection with .net applications The best choice if you are .Net developer is SQL server, it demonstrates the best performance, easy to establish secure and stable connections. In addition it offers good security features
Simplicity It is more simple to deal with MySQL server It is less simple to deal with Microsoft SQL server
Connection More difficult to connect to MySQL database, the best and the only way is to use ODBC the 3.51 ODBC connector and the rest, I mean OLEDB connectors, the recent ODBC connectors versions and event the others tools represent a lot of bugs and they are not stables There are several ways to connect to Microsoft SQL server. The .Net environment provides special libraries to deal only with SQL server connections. More over you can use ODBC and even OLEDB for the older Microsoft SQL server versions.

Connecting to a MySQL database is not something difficult, but when visiting several forums you can remark that the question is frequently posted by a lot of people, I think, as they are .Net developers, they deal almost all the time with an SQL Server database to store data, the other database types are not used. I, personally, saw this problematic in a dozen of forums, English forums, French forums and German forum too. Always the same question like "how to pass parameter" and "connect to a MySQL database from a .Net application" can be seen in a forum.

Therefore, I will provide more than one method to deal with the issue. In this first article, we will see the simplest method to deal with the problem. In a second article, I will provide a second solution. Let's begin the trip!!!

First, if you have MySQL server already installed on your machine then it is OK, else, if you want to start from the beginning then you have to install MySQL server first. If you are a PHP programmer then you will be familiar with this product. In our case, we are concerned only by MySQL database server, I personally use PhpMyAdmin in order to create and request data within MySQL format. You can also download MySQL server directly from www.mysql.com, the MySQL official web site. Moreover, you can download other kind of management consoles also provided by the same web site or you can simply Google it, find the suitable management console for MySQL databases and download it or finally, it is possible to deal with MySQL database system using what I can  say the "ugly" console. But as a part of this tutorial, I will deal with MySQL via PhpMyAdmin. Anyway, the installation, the configuration and the creation of MySQL databases are out of the scope of this tutorial. There are a lot of articles about those topic. If you are interested in this kind of databases you can simply take a look on tutorials in www.mysql.com. But for the moment, our unique concern is how to connect to a MySQL database from .Net environment.  In our case we suppose that we have a database that is called database, using localhost as server, me as user id and me as password. This database contains a table called user; this last one contains two fields UserID, and Password which I have already populated with some data.

Walkthrough:

First, you have to download the MySQL ODBC connector 3.51 from http://dev.mysql.com/downloads/connector/odbc/3.51.html and then install it. There is a newer version which is the ODBC connector 5.1 but I don't advise to use it for the moment because it is not stable, I personally had problems with the ODBC connector 5.1. After downloading and installing the connector, create a data source name DSN, to do so follow those steps:

  1. Go to Start > Configuration panel > Administration tools > ODBC data sources

  2. Select user data sources tab, then click Add



    Figure 1

  3. Then the below window appears, then select MySQL 3.51 Driver and click finish



    Figure 2

  4. Add your database parameters, namely the data source name (The alias used later in the connection string "database" in this case), the description, the server name (Localhost if you use a local machine or the server name if you use a distant machine), the user name (root for example or you can create a new user from within MySQL Server), the password and finally database name.

  5. You can test the connection by clicking Test button, if it is OK then click OK, then click OK again to 



    Figure 3 

Once the DSN is configured, move to Visual studio and perform the following tasks:

Create a new Console application project then add a new class to the new project and name it ODBCClass, finally implement it as below:

using System;

using System.Text;

using System.Data;

using System.Data.Odbc; 

 

namespace MysqlProj_1

{

class ODBCClass : IDisposable

{

/// <summary>

/// OdbcConnection : This is the connection

/// </summary>

OdbcConnection oConnection;

/// <summary>

/// OdbcCommand : This is the command

/// </summary>

OdbcCommand oCommand;

/// <summary>

/// Constructor: This is the constructor

/// </summary>

/// <param name="DataSourceName">string: This is the data source name</param>

public ODBCClass(string DataSourceName )

{

//Instantiate the connection

oConnection = new OdbcConnection("Dsn=" + DataSourceName);

try

{

//Open the connection

oConnection.Open();

//Notify the user that the connection is opened

Console.WriteLine("The connection is established with the database");

 

}

catch (OdbcException caught)

{

Console.WriteLine(caught.Message);

Console.Read();

}

}

/// <summary>

/// void: It is used to close the connection if you work within disconnected

/// mode

/// </summary>

public void CloseConnection()

{

oConnection.Close();

}

/// <summary>

/// OdbcCommand: This function returns a valid odbc connection

/// </summary>

/// <param name="Query">string: This is the SQL query</param>

/// <returns></returns>

public OdbcCommand GetCommand(string Query)

{

oCommand = new OdbcCommand();

oCommand.Connection = oConnection;

oCommand.CommandText = Query;

return oCommand;

}

/// <summary>

/// void: This method close the actual connection

/// </summary>

public void Dispose()

{

oConnection.Close();

}

 

}

}

If you want to work with connecting mode then do implement the main method as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.Odbc;

 

namespace MysqlProj_1

{

    class Program

    {

        static void Main(string[] args)

        {

            using (ODBCClass o = new ODBCClass())

            {

                OdbcCommand oCommand = o.GetCommand("select * from user");

                OdbcDataReader oReader = oCommand.ExecuteReader();

                while (oReader.Read())

                {

                    Console.WriteLine(oReader[0] + " " + oReader[1]);

                }

                Console.Read();

            }

        }

    }

}

Else, if you want to work with disconnected mode then implement the main method as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.Odbc;

 

namespace MysqlProj_1

{

    class Program

    {

        static void Main(string[] args)

        {

            using (ODBCClass o = new ODBCClass())

            {

                OdbcCommand oCommand = o.GetCommand("select * from user");

                OdbcDataAdapter oAdapter = new OdbcDataAdapter(oCommand);

                DataSet ds = new DataSet();

                oAdapter.Fill(ds);

                //TO DO : Make use of the data set

            }

        }

    }

}

This is one of the two methods used to connect and deal with a MySQL database. In subsequent articles, I will expose other techniques to achieve the same task, for instance, you shouldn't miss the second method to connect via ODBC without using data source name.

GoodDotneting!!!

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
 
Bechir Bejaoui

The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT".

He also holds:

MCPD enteprise solutions developement 3.5 certification and MCTS distibuted application developement 2.0

 He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.

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:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
how to connect to mysql server on web by ashu On December 9, 2011
My application running on local machine requires connection to be established with MYSQL server database which is hosted on web. I am configuring odbc connector in my machine for dsn connectivity. What should i write in TCP/IP server field (url or ip add of site). The web server is having phpadmin & I have address of cpanel. Thanks in advance
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.