Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
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
DevExpress UI Controls
Search :       Advanced Search »
Home » ADO.NET & Database » Connect to MySQL database - via ODBC without using DSN: Part II

Connect to MySQL database - via ODBC without using DSN: Part II

In order to connect to on MySQL method, I propose this more flexible solution, thus, it enables us to customize the connection parameters in one hand, moreover, it enables us to choose which mode should we use. I mean, ADO connected mode using data reader or disconnected mode using data adapter and data set.

Author Rank :
Page Views : 8538
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  
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


In order to connect to on MySQL method, I propose this more flexible solution, thus, it enables us to customize the connection parameters in one hand, moreover, it enables us to choose which mode should we use. I mean, ADO connected mode using data reader or disconnected mode using data adapter and data set.

Walkthrough:

Remarque: Of course, I suppose that MySQL server is installed in your machine, a database already exists, and all information and permissions to use the given database are ready.

Here is a class that helps you connect and deal with your MySQL database:

using System;

using System.Text;

using System.Data;

using System.Data.Odbc;

 

namespace MySqlProj

{

/* The class implements IDisposable interface

* inorder to close the connection once the class instance

is disposed*/

public class ODBCClass : IDisposable

{

 //This is the password private field

    private string _Password;

//The server name

public string Server { get; set; }

//The port number

public string Port { get; set; }

//The data base name

public string DataBaseName { get; set; }

//The user name

public string UserID { get; set; }

//The password is only set for security issues

public string Password

{

    set { _Password = value; }

}

//Set a query

public string Query { get; set; }

//Define a private connection

private OdbcConnection myConnection;

//Define a command

OdbcCommand myCommand;

/// <summary>

/// This is the constructor

/// </summary>

/// <param name="Server">string: The server name</param>

/// <param name="Port">string: The port number</param>

/// <param name="DataBaseName">string: The data base name</param>

/// <param name="UserID">string: The user name</param>

/// <param name="Password">string: The password</param>

public ODBCClass(string Server, string Port, string DataBaseName,string UserID,string Password, string Query)

{

    this.Server = Server;

    this.Port = Port;

    this.DataBaseName = DataBaseName;

    this.UserID = UserID;

    this.Password = Password;

    this.Query = Query;

 

   

    myConnection = new OdbcConnection();

    myConnection.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=" + Server + "; PORT=" + Port + ";DATABASE= " + DataBaseName + ";UID= " + UserID + ";PWD=" + Password;

    try

    {

        //Open the connection

        myConnection.Open();

        //Notify the user that the connection is opened

        Console.WriteLine("Connected to the data base");

        //Create a new command object

        myCommand = new OdbcCommand(Query, myConnection);

        /* CommandBehavior.CloseConnection option forces the connection to close if

         somethig id wrong*/

    }

    catch (OdbcException caught)

    {

        //TO DO Deal with  the exception

    }

    catch (InvalidOperationException caught)

    {

        //TO DO Deal with  the exception

    }

}

/// <summary>

/// OdbcCommand : This method returns a command object

/// </summary>

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

/// <returns>returns an OdbcCommand</returns>

 

/// <summary>

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

/// mode

/// </summary>

public void CloseConnection()

{

  myConnection.Close();

}

public OdbcCommand GetOdbcCommand()

{

 //Returns a command object  

 return myCommand;

}

//When the object is disposed the connection is  closed

public void Dispose()

{

    myConnection.Close();

}

}

}

Now, open a new Project>Console application and name it as you like, create a new empty class and name it ODBCClass, then copy and paste the above class in the code editor.

Once this is done you can choose either to work within a connected mode, if you do so then implement the main method as follows:

using System.Data.Odbc;

 

namespace MySqlProj

{

 class Program

 {

    static void Main(string[] args)

    {

      using (ODBCClass o = new ODBCClass("localhost", "3306", "database", "me", "me","select * from user"))

            {

                OdbcCommand comm = o.GetOdbcCommand("Select * from user");

                OdbcDataReader oReader = comm.ExecuteReader();

                while (oReader.Read())

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

                Console.Read();

            }

     }

  }

}

If you want to do the same think but in disconnected mode then implement the Main method as follows:

using System;

using System.Text;

using System.Data;

using System.Data.Odbc;

 

namespace MySqlProj

{

    class Program

    {

     static void Main(string[] args)

     {

      using (ODBCClass o = new ODBCClass("localhost", "3306", "database", "me", "me"))

            {

                OdbcCommand comm = o.GetOdbcCommand("Select * from user");

                OdbcDataAdapter oAdapter = new OdbcDataAdapter(comm);

                DataSet Ds = new DataSet();

                oAdapter.Fill(Ds);

    

                Console.WriteLine("Data set is filled you can make use of it now");

                //TO DO  Make use of the populated data set

                Console.Read();

               

            }

     }

   }

}

That's it

God dotneting!!!

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:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
disconnected Mode Main implementation by Brent On September 14, 2009
Hello,

This was a nice article. But your ODBC class has 6 parameters. In the disconnected mode Main implementation you only have 5 arguments.

Thank You,

Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.