miercuri, 30 noiembrie 2011

MySql .NET connector example

How to connect to a MySQL database using the mysql .NET connector in C#.

Download and install the MySql.Net connector.

Add a reference to it in your project, that is - click on "Project'->'Add reference', on your '.net assembly browser' tab and choose the library, make sure you're adding the 'Assembly' (the type is shown in the window just after you select the file).

And here is sample code from a working program:

using MySql.Data.MySqlClient;

namespace my_namespace_whatever
{
    public partial class MainForm : Form
    { 
        private MySqlConnection MyConn;
        private MySqlCommand MyCom;
        private MySqlDataAdapter MyDR;
        private string ConnStr;

        public MainForm()
        {
            InitializeComponent();
            // now the interesting part
            ConnStr = "SERVER=localhost;DATABASE=my_database;UID=my_user;PWD=my_password;";
            MyConn = new MySqlConnection(ConnStr);
            if (MyConn.State == ConnectionState.Closed)
            {
               MyConn.Open();
            }
            if (MyConn.State != ConnectionState.Open)
            {
                MessageBox.Show("Could not connect");
            }

            // A.S.O

  }
}

Niciun comentariu:

Trimiteți un comentariu