Saving and Retrieving Data in the Database Using C# and MySQL Database

In this tutorial, I will teach you how to save and retrieve data in the database using C#.net and MySQL Database. This method will help you add the user information in the MySQL database and display it onto the Datagridview.

Let’s get started:

Create a database in the MySQL and name it “dbuser“.

Do the following query for creating a table in the database that you have created.

1

2

3

4

5

6

7

8

CREATE TABLE IFNOTEXISTS`tblusers`(

`ID`int(11)NOTNULLAUTO_INCREMENT,

`UNAME`varchar(40)NOTNULL,

`UUSERNAME`varchar(40)NOTNULL,

`UPASSWORD`varchar(90)NOTNULL,

`UTYPE`varchar(30)NOTNULL,

PRIMARY KEY(`ID`)

)ENGINE=InnoDB DEFAULTCHARSET=latin1 AUTO_INCREMENT=2;

After that, open Microsoft Visual Studio 2008 and create a new windows form application for C#. Then, do the form just like this.

After setting up the form, go to the solution explorer and hit the “view code” to fire the code editor.

In the code editor, do the following codes for declaring the classes and variables.

1

2

3

4

5

6

7

8

9

10

//initialize sql connection

MySqlConnection con=newMySqlConnection();

//initialize all classes

MySqlCommand cmd=newMySqlCommand();

MySqlDataAdapter da=newMySqlDataAdapter();

DataTable dt=newDataTable();

//declaring variables

stringquery;

intres;

After declaring the classes and variables, do the following codes for establishing the connection between MySQL database and C#.net

Itsourcecode is designed to help those newbie programmers to widen their knowledge and enhance their skills in programming through free source code from different programming languages such as VB.net, PHP, Java, HTML, CSS, etc.