Sunday, November 18, 2012

Connect to MySQL Database using C#

//Retrieve data from MySQL database using native connection
//Install  MySQL Connector Net 6.3.7 or higher before using the code below
//Project->Add References->Browse->browse MySQL.Data.dll,MySQL.Data.Entity.dll,MySQL.Web.dll
//from C:\Program Files (x86)\MySQL\MySQL Connector Net 6.3.7\Assemblies\v4.0

using MySql.Data;
using MySql.Data.MySqlClient;

MySqlDataAdapter da;
DataSet ds;

MySqlConnection conn = new MySqlConnection("server=localhost;user=UserName;database=DBName;port=3306;password=UserPassword");
conn.Open();
da = new MySqlDataAdapter(Replace_with_your_String_Selection, conn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);

ds = new DataSet();
da.Fill(ds, Replace_with_Table_Name);
conn.Close();

//MessageBox.Show(ds.Tables["tblName"].Rows[0].ItemArray[1].ToString());

//Insert, Update, Delete record from MySQL database
//Install  MySQL Connector Net 6.3.7 or higher before using the code below
//Project->Add References->Browse->browse MySQL.Data.dll,MySQL.Data.Entity.dll,MySQL.Web.dll //from C:\Program Files (x86)\MySQL\MySQL Connector Net 6.3.7\Assemblies\v4.0

using MySql.Data;
using MySql.Data.MySqlClient;

MySqlConnection conn = new MySqlConnection("server=localhost;user=UserName;database=DBName;port=3306;password=UserPassword");
conn.Open();
MySqlCommand cmd = new MySqlCommand(Replace_with_your_INSERT_UPDATE_DELETE_Command, conn);
cmd.ExecuteNonQuery();
conn.Close();

// dg.ItemsSource = ds.Tables["tblName"].DefaultView;

0 comments: