Tuesday, December 25, 2018

C# Visual Studio Connect to MySQL Database - Use Select, Insert, Update and delete - 01


In this tutorial I show you how to connect to a mySQL database using C# and Visual Studio. I show you a few useful queries you can run: Select, Insert, Update and delete in order to use the data in the mySQL database. This video I make connection and Insert. Here include
source code and reference.



Database connection class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace TestProject
{
    class DBConnect
    {

        public static MySqlConnection ConnectDB()
        {

            try
            {
                string server = "localhost";
                string database = "testproject";
                string uid = "root";
                string password = "";
                string connectionString;
                connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
                MySqlConnection connection = new MySqlConnection(connectionString);
                return connection;
            }
            catch (MySqlException ex)
            {
                //  MessageBox.Show(ex.Message);
                return null;
            }
        }
    }
}


C# form with query and code



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace TestProject
{
    public partial class Form1 : Form
    {

        MySqlConnection con = null;
        public Form1()
        {
            InitializeComponent();
            con = DBConnect.ConnectDB();

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnadd_Click(object sender, EventArgs e)
        {
            con.Open();
            try
            {
                string qu = "INSERT INTO `test`(`id`, `name`) VALUES ('"+txtid.Text+"', '"+txtnames.Text+"')";
                MySqlCommand cm = new MySqlCommand(qu, con);
                cm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

            }
            con.Close();
        }
    }
}

No comments:

Post a Comment