Visual Studio 2010 Hosting :: Connect to MySQL Database from Visual Studio VS2010

Posted by mbridge on Geeks with Blogs See other posts from Geeks with Blogs or by mbridge
Published on Tue, 14 Dec 2010 01:20:11 GMT Indexed on 2010/12/16 4:11 UTC
Read the original article Hit count: 798

Filed under:
So, in order to connect to a MySql database from VS2010 you need to

1. download the latest version of the MySql Connector/NET from http://www.mysql.com/downloads/connector/net/

2. install the connector (if you have an older version you need to remove it from Control Panel -> Add / Remove Programs)

3. open Visual Studio 2010

4. open Server Explorer Window (View -> Server Explorer)



5. use Connect to Database button

6. in the Choose Data Source windows select MySql Database and press Continue



7. in the Add Connection window
- set server name: 127.0.0.1 or localhost for MySql server running on local machine or an IP address for a remote server
- username and password
- if the the above data is correct and the connection can be made, you have the possibility to select the database



If you want to connect to a MySql database from a C# application (Windows or Web) you can use the next sequence:

//define the connection reference and initialize it
MySql.Data.MySqlClient.MySqlConnection msqlConnection = null;
msqlConnection = new MySql.Data.MySqlClient.MySqlConnection(“server=localhost;user id=UserName;Password=UserPassword;database=DatabaseName;persist security info=False”);
    //define the command reference
MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand();
    //define the connection used by the command object
msqlCommand.Connection = this.msqlConnection;
    //define the command text
msqlCommand.CommandText = "SELECT * FROM TestTable;";
try
{
    //open the connection
    this.msqlConnection.Open();
    //use a DataReader to process each record
    MySql.Data.MySqlClient.MySqlDataReader msqlReader = msqlCommand.ExecuteReader();
    while (msqlReader.Read())
    {
        //do something with each record
    }
}
catch (Exception er)
{
    //do something with the exception
}
finally
{
    //always close the connection
    this.msqlConnection.Close();
}
.
 

© Geeks with Blogs or respective owner