Friday, October 19, 2012

Connecting to MySQL database using C# and .Net

Connecting to MySQL database using C# and .Net

Connecting to MySQL database using C# and .Net
Download MySQL script file
Download Sample
This article shows you how you can connect to MySQL database using MySQL Connector for .Net. I will also show you how you can update mysql database records using C#.

Prerequisites for running sample

  • Visual Studio 2005 or Visual Studio 2008
  • MySQL database installed on your local machine or remote host.
  • MySQL database admin tool that allows you to create database and run sql statements. I am using phpMyAdmin which is a web interface.

Getting Started

  • Go to MySQL admin tool, and create a new database, call it inventorydb
  • Download MySQL script from following link. This is a .sql file. It contains items table structure and data.
    Download MySQL script file
    Open this file with MySQL Admin tool or copy paste sql syntax from this file into MySQL Admin tool. Run it and it should create items table in inventorydb database.
    Connecting to MySQL database using C# and .Net


  • For Visual Studio, you need to install MySQL Connector for .Net which is basically a .Net library to support MySQL database connectivity in .Net. Go to following link to download connector and install it.
    http://dev.mysql.com/downloads/connector/net
    When you install connector make sure that you close Visual Studio before installing.
  • Once MySQL connector is installed successfully on your computer, download sample from following link and extract it in some folder. Download Sample
  • Open sample solution file with visual studio.
  • Inside Solution Explorer, open App.Config file and change connection string so that it points to MySQL database that you created before. Change database user name and password in connection string as per your database instance.
    Connection String

  • Run sample and it should give you list of items in grid.You can update, insert or delete items from this list.

Sourcecode description

Source code of this sample is very straight forward.
  • Initialize mysql connection using following code,
    1.//Initialize mysql connection
    2.connection = new MySqlConnection(ConnectionString);
    3. 
    4.//Get all items in datatable
    5.DTItems = GetAllItems();
  • GetAllItems() function returns all items from database table,
    01.//Get all items from database into datatable
    02.DataTable GetAllItems()
    03.{
    04.try
    05.{
    06.//prepare query to get all records from items table
    07.string query = "select * from items";
    08.//prepare adapter to run query
    09.adapter = new MySqlDataAdapter(query, connection);
    10.DataSet DS = new DataSet();
    11.//get query results in dataset
    12.adapter.Fill(DS);
    13..
    14..
    15..
    16.//return datatable with all records
    17.return DS.Tables[0];
    18.}
  • After retrieving all items in a datatable, fill grid view using datatable,
    1.dataGridView1.DataSource = DTItems;
  • When initializing dataset, set update, insert and delete commands with adapter.
    01..
    02..
    03..
    04.// Set the UPDATE command and parameters.
    05.adapter.UpdateCommand = new MySqlCommand(
    06."UPDATE items SET ItemName=@ItemName, Price=@Price, AvailableQuantity=@AvailableQuantity, Updated_Dt=NOW() WHERE ItemNumber=@ItemNumber;",connection);
    07.adapter.UpdateCommand.Parameters.Add("@ItemNumber", MySqlDbType.Int16, 4, "ItemNumber");
    08.adapter.UpdateCommand.Parameters.Add("@ItemName", MySqlDbType.VarChar, 100, "ItemName");
    09.adapter.UpdateCommand.Parameters.Add("@Price", MySqlDbType.Decimal, 10, "Price");
    10.adapter.UpdateCommand.Parameters.Add("@AvailableQuantity", MySqlDbType.Int16, 11, "AvailableQuantity");
    11.adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
    12. 
    13.// Set the INSERT command and parameter.
    14.adapter.InsertCommand = new MySqlCommand(
    15."INSERT INTO items VALUES (@ItemNumber,@ItemName,@Price,@AvailableQuantity,NOW());",connection);
    16.adapter.InsertCommand.Parameters.Add("@ItemNumber", MySqlDbType.Int16, 4, "ItemNumber");
    17.adapter.InsertCommand.Parameters.Add("@ItemName", MySqlDbType.VarChar, 100, "ItemName");
    18.adapter.InsertCommand.Parameters.Add("@Price", MySqlDbType.Decimal, 10, "Price");
    19.adapter.InsertCommand.Parameters.Add("@AvailableQuantity", MySqlDbType.Int16, 11, "AvailableQuantity");
    20.adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
    21. 
    22.// Set the DELETE command and parameter.
    23.adapter.DeleteCommand = new MySqlCommand(
    24."DELETE FROM items " + "WHERE ItemNumber=@ItemNumber;", connection);
    25.adapter.DeleteCommand.Parameters.Add("@ItemNumber", MySqlDbType.Int16, 4, "ItemNumber");
    26.adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
    27..
    28..
    29..
  • When Save button is clicked, we need to update adapter in order to save records. Note that when adapter is updated, corresponding commands (insert, update or delete) are executed against database based on operations that you have done on grid.
    01.private void btnSave_Click(object sender, EventArgs e)
    02.{
    03.try
    04.{
    05.//Save records in database using DTItems which is datasource for Grid
    06.adapter.Update(DTItems);
    07..
    08..
    09..
  • When Delete button is clicked, we need to remove row from datatable. After that update adapter to save records.
    01.private void btnDelete_Click(object sender, EventArgs e)
    02.{
    03.if (dataGridView1.SelectedRows.Count > 0)
    04.{
    05.//Delete a row from grid first.
    06.dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
    07. 
    08.//Save records again. This will delete record from database.
    09.adapter.Update(DTItems);
    10..
    11..
    12..

No comments:

Post a Comment