Click here to Skip to main content
Click here to Skip to main content

C# ASP.NET MySQL Connection Tutorial with MySQL Connector

By , 28 Mar 2012
Sign Up to vote
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

In order to connect to MySQL Server with .NET in C# or ASP.NET:

  • You need to download MySQL Connector/Net .
  • After you add a reference to your project, it is probably in C:\Program Files\MySQL\MySQL Connector Net 5.0.7\Binaries\.NET 2.0 folder, add the MySql.Data.dll file as a reference.
  • Make your connection string, the following code will shows a standard MySQL connection string.
  • using MySql.Data.MySqlClient;
    public static string GetConnectionString()
    {
      string connStr = String.Format("server={0};user id={1}; password={2};" + 
        "database=yourdb; pooling=false", "yourserver",
        "youruser", "yourpass");
    
      return connStr;
    }
  • Then create an instance from MySql.Data.MySqlClient.MySqlConnection as shown below.
  • MySql.Data.MySqlClient.MySqlConnection mycon = 
      new MySqlConnection( GetConnectionString());
  • Then try to open the MySqlConnection.
  • if(mycon .State != ConnectionState.Open)
    try
    {
      mycon .Open();
    }
    catch (MySqlException ex)
    {
      throw (ex);
    }

So simple as you see, It is always better to do this in data access layer also called DAL.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Yaseer Arafat
Software Developer (Senior)
Bangladesh Bangladesh
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 1memberaryaverman1888-Aug-13 1:45 
GeneralRe: My vote of 1memberYaseer Arafat18-Aug-13 12:02 
QuestionDrivermemberMohamad777-Aug-13 1:03 
AnswerRe: DrivermemberYaseer Arafat18-Aug-13 12:01 
QuestionThanksmemberYaseer Arafat8-Mar-13 6:47 
Generalhttp://dotnetnukes.blogspot.in/memberchitranjan singh rathore1-Feb-13 1:00 
General<a href="http://dotnetnukes.blogspot.in/<code></code>"></a>memberchitranjan singh rathore1-Feb-13 0:56 
QuestionLogin pagememberSandunika Nilmadi9-Dec-12 19:10 
AnswerRe: Login pagememberYaseer Arafat8-Mar-13 6:40 
SuggestionAdd source code pleasememberragunaat919-Jul-12 3:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

| Advertise | Privacy | Mobile
Web02 | 2.7.131126.1 | Last Updated 28 Mar 2012
Article Copyright 2012 by Yaseer Arafat
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid