Add data to database (C#)

Open your previous Windows application we made.

Add Fields to your windows form where you need to add to database.

As a example hear, I used First Name, Last Name, Age fields to add data.

In hear I added 3 labels and 3 TextBox to my form

I change the TextBox names to ,

  • First Name - txtFName
  • LastName - txtLName
  • Age - txtAge
Add a button, I name it as "Save"

Double click on button & type this code hear..

string conString = "datasource=localhost;port=3306;username=root;password=";

            string Query = "insert into blog.empdata(fname,lName,age) values('" + this.txtFName.Text + "','"+this.txtLName.Text+"','"+this.txtAge.Text+"');";

            MySqlConnection conDataBase = new MySqlConnection(conString);

            MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);

            MySqlDataReader myReader;

            try

            {

                conDataBase.Open();

                myReader = cmdDataBase.ExecuteReader();

                MessageBox.Show("Saved");

                while (myReader.Read())

                {


                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }




If your code is correct Message box will show the message "Saved"

That mean your data is saved in your database..


My data saved in my database


Before you try this you must have made a database named blog(something else ) and table named empdata(something else)

If you want to know how make a database please follow this link Working with MySQL Workbench

4 comments: