Connecting To MySQL Database Using C
Connecting To MySQL Database Using C
NET
By Shabdar Ghata | 7 Apr 2010
C#.NETMySQL
This article shows you how to connect to MySQL database using MySQL Connector
for .NET
Part of The SQL Zone sponsored by
See Also
1 2 3 4 5
/w EPDw UKMjExO
/w EWCAKAtK/kB
This article shows you how to connect to MySQL database using MySQL Connector
for .NET. I will also show you how you can update mysql database records using
C#.
Getting Started
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 the 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.
Download sample
Run the sample and it should give you a list of items in grid. You can update,
insert or delete items from this list.
Source Code Description
After retrieving all items in a datatable, fill grid view using datatable:
dataGridView1.DataSource = DTItems;
When initializing dataset, set update, insert and delete commands with
adapter.
.
.
.
// Set the UPDATE command and parameters.
adapter.UpdateCommand = new MySqlCommand(
"UPDATE items SET ItemName=@ItemName, Price=@Price, _
AvailableQuantity=@AvailableQuantity, Updated_Dt=NOW() _
WHERE ItemNumber=@ItemNumber;",connection);
adapter.UpdateCommand.Parameters.Add("@ItemNumber", _
MySqlDbType.Int16, 4, "ItemNumber");
adapter.UpdateCommand.Parameters.Add_
("@ItemName", MySqlDbType.VarChar, 100, "ItemName");
adapter.UpdateCommand.Parameters.Add_
("@Price", MySqlDbType.Decimal, 10, "Price");
adapter.UpdateCommand.Parameters.Add_
("@AvailableQuantity", MySqlDbType.Int16, 11, "AvailableQuantity");
adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;