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.
- 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.
- 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,
- GetAllItems() function returns all items from database table,
- After retrieving all items in a datatable, fill grid view using datatable,
- When initializing dataset, set update, insert and delete commands with adapter.
- 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.
- When Delete button is clicked, we need to remove row from datatable. After that update adapter to save records.
No comments:
Post a Comment