NEWS

[C#] Hướng dẫn Thêm, xóa, sửa với PostgreSQL winform

[C#] Hướng dẫn Thêm, xóa, sửa với PostgreSQL winform
Đăng bởi: Thảo Meo - Lượt xem: 2082 14:34:27, 08/06/2023C#   In bài viết

Xin chào các bạn bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách thêm, xóa sửa làm việc với cơ sở dữ liệu PostgreSQL trong C# winform.

[C#] How to CRUD PostgreSQL in Winform

screenshot_1686208193

Vậy PostgreSQL là gì?

PostgreSQL là một hệ quản trị cơ sở dữ liệu mở nguồn mạnh mẽ và phổ biến. Với khả năng xử lý dữ liệu phức tạp, tính bảo mật cao và cộng đồng hỗ trợ đông đảo, PostgreSQL đã trở thành một lựa chọn hàng đầu cho nhiều ứng dụng từ nhỏ đến lớn.

Trong bài viết này, chúng ta sẽ tìm hiểu về ưu nhược điểm của PostgreSQL.

Ưu điểm của PostgreSQL:

  1. Độ tin cậy cao: PostgreSQL có khả năng xử lý cùng lúc hàng ngàn kết nối đồng thời và cung cấp tính toàn vẹn dữ liệu cao. Nó hỗ trợ các tính năng như ACID (Atomicity, Consistency, Isolation, Durability) để đảm bảo tính nhất quán của dữ liệu và giảm thiểu rủi ro mất dữ liệu.

  2. Đa nền tảng: PostgreSQL có thể hoạt động trên nhiều hệ điều hành như Windows, macOS và các phiên bản của Linux. Điều này cho phép bạn triển khai ứng dụng của mình trên nền tảng ưa thích của bạn mà không bị ràng buộc.

  3. Khả năng mở rộng: PostgreSQL cho phép mở rộng dễ dàng bằng cách sử dụng các tính năng như Replication, Sharding và Partitioning. Bạn có thể mở rộng hệ thống của mình để đáp ứng tải công việc ngày càng tăng mà không phải thay đổi cấu trúc cơ sở dữ liệu hiện có.

  4. Cộng đồng hỗ trợ lớn: PostgreSQL có một cộng đồng lớn và nhiều người dùng trên toàn thế giới. Điều này mang lại nhiều lợi ích như sự hỗ trợ từ cộng đồng, việc chia sẻ kiến thức và khả năng tương tác với những người có cùng quan tâm.

Nhược điểm của PostgreSQL:

  1. Hiệu suất có thể bị ảnh hưởng: Mặc dù PostgreSQL có hiệu suất tốt, nhưng trong một số trường hợp đặc biệt với khối lượng dữ liệu lớn, hiệu suất có thể giảm xuống. Điều này có thể đòi hỏi tối ưu hóa và điều chỉnh cấu hình để đạt được hiệu suất tốt nhất.

  2. Khó khăn trong việc quản lý: PostgreSQL có một số tính năng phức tạp và yêu cầu kiến thức kỹ thuật sâu để cài đặt và quản lý. Điều này có thể làm tăng độ phức tạp của quá trình triển khai và bảo trì hệ thống.

  3. Hạn chế về hỗ trợ công cụ: So với một số hệ quản trị cơ sở dữ liệu khác như MySQL, PostgreSQL có ít công cụ hỗ trợ phong phú hơn. Một số công cụ phổ biến vẫn chưa hỗ trợ PostgreSQL hoặc hỗ trợ không đầy đủ tính năng.

  4. Tài liệu và khóa học có thể hạn chế: Dù có cộng đồng rộng lớn, nhưng tài liệu và khóa học chất lượng cao và có cấu trúc cho PostgreSQL có thể khá hạn chế so với một số giải pháp cơ sở dữ liệu phổ biến khác.

P/s: Kết lại, PostgreSQL là một hệ quản trị cơ sở dữ liệu mạnh mẽ và linh hoạt với nhiều ưu điểm như độ tin cậy cao, khả năng mở rộng và cộng đồng hỗ trợ lớn.

Tuy nhiên, nó cũng có một số nhược điểm như hiệu suất có thể bị ảnh hưởng và độ phức tạp trong việc quản lý.

Với việc hiểu rõ về ưu nhược điểm này, bạn có thể đưa ra quyết định thông minh khi sử dụng PostgreSQL cho dự án của mình.

Dưới đây là hình ảnh giao diện demo ứng dụng c#:

POSTGRESQL

Video hướng dẫn thực hiện step by step:

Đầu tiên, các bạn cần cài đặt thư viện: Dapper và Npgsql từ nuget vào project của mình.

NuGetInstall-Package Npgsql -Version 8.0.0-preview.4

Cài đặt 2 thư viện Dapper:

NuGetInstall-Package Dapper -Version 2.0.123
NuGetInstall-Package Dapper.Contrib -Version 2.0.78

Tiếp đến, các bạn tạo 1 class Constant.cs, ở class này chúng ta sẽ khai báo câu lệnh kết nối đến cơ sở dữ liệu PostgreSQL.

namespace CRUDPostgresDB
{
    public  class constants
    {
        public const string PostgresConnection = "Host=localhost;Port=8888;Username=postgres;Password=thao123;Database=DemoCRUD";
    }
}

Tạo tiếp, một class PostgreHelper.cs, class này chứa các câu lệnh làm việc với postgre như: insert, update, delete, getall, getbyid.

namespace CRUDPostgresDB
{
    public  class PostgresHelper
    {

        public static T GetById<T>(int id) where T : class
        {
            var dataSourceBuilder = new NpgsqlDataSourceBuilder(constants.PostgresConnection);
            var dataSource = dataSourceBuilder.Build();

            using (var connection = dataSource.OpenConnection())
            {

                try
                {
                    return connection.Get<T>(id);
                }
                catch (Exception ex)
                {
                    return null;
                }

            }
        }

        public static List<T> GetAll<T>() where T : class
        {
            var dataSourceBuilder = new NpgsqlDataSourceBuilder(constants.PostgresConnection);
            var dataSource = dataSourceBuilder.Build();

            using (var connection = dataSource.OpenConnection())
            {
             
                try
                {
                    return connection.GetAll<T>().ToList();
                }
                catch (Exception ex)
                {
                    return new List<T>();
                }
               
            }
        }

        public static  long Insert<T>(T entityToInsert) where T : class
        {
            var dataSourceBuilder = new NpgsqlDataSourceBuilder(constants.PostgresConnection);
            var dataSource = dataSourceBuilder.Build();        

            using (var connection =  dataSource.OpenConnection())
            {             
                long re = 0;
                try
                {
                    re = connection.Insert(entityToInsert);
                }
                catch (Exception ex)
                {
                    re = 0;
                    XtraMessageBox.Show(ex.Message);
                }
                return re;
            }
        }

        public static bool Update<T>(T entityToUpdate) where T : class
        {
            var dataSourceBuilder = new NpgsqlDataSourceBuilder(constants.PostgresConnection);
            var dataSource = dataSourceBuilder.Build();

            using (var connection = dataSource.OpenConnection())
            {
                var result = false;
                try
                {
                    result = connection.Update(entityToUpdate);
                }
                catch (Exception ex)
                {
                    result = false;
                    XtraMessageBox.Show(ex.Message);
                }
                return result;
            }
        }

        public static bool Delete<T>(T entityToDelete) where T : class
        {
            var dataSourceBuilder = new NpgsqlDataSourceBuilder(constants.PostgresConnection);
            var dataSource = dataSourceBuilder.Build();

            using (var connection = dataSource.OpenConnection())
            {
                bool success = false;
                try
                {
                    success = connection.Delete(entityToDelete);
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message);
                }
                return success;
            }
        }
    }
}

Tiếp đến, tạo một đối tượng Employee.cs

namespace CRUDPostgresDB.Models
{
    [Table("tbl_employees")]
    public class Employee
    {
        [Key]
        public int id {  get; set; }    
        public string fullname { get; set; }
        public string phone { get; set; }
        public string address { get; set; }
    }
}

Do trong bài viết này chúng ta sử dụng Dapper.contrib nên chúng ta cần khai báo tên bảng table và khóa vào trong class Employee.cs

Source code c# giao diện FormMain.cs

using CRUDPostgresDB.Models;
using DevExpress.XtraEditors;
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;

namespace CRUDPostgresDB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            var data = PostgresHelper.GetAll<Employee>();

            gridControl1.DataSource = data; 
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            var fullname = txtFullname.Text;
            var address = txtAddress.Text;
            var phone = txtPhone.Text;
            if(string.IsNullOrEmpty(fullname) )
            {
                XtraMessageBox.Show("Please input your fullname.");
                txtFullname.Focus();
                return;
            }

            var newEmployee = new Employee();
            newEmployee.fullname = fullname;
            newEmployee.address = address;
            newEmployee.phone   = phone;

            PostgresHelper.Insert(newEmployee);
            txtFullname.Text = "";
            txtAddress.Text = "";
            txtPhone.Text = "";
            txtFullname.Focus();
            // refresh data to gridview
            btnGetData_Click(null, null);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            var fullname = txtFullname.Text;
            var address = txtAddress.Text;
            var phone = txtPhone.Text;
            var id = Convert.ToInt32(txtID.Text);
            var updateEmployee = new Employee();
            updateEmployee.fullname = fullname;
            updateEmployee.address = address;
            updateEmployee.phone = phone;
            updateEmployee.id = id; 

            PostgresHelper.Update(updateEmployee);
            // refresh data to gridview
            btnGetData_Click(null, null);


        }

        private void btnGetByID_Click(object sender, EventArgs e)
        {
            var id = Convert.ToInt32(txtID.Text);
            var employee = PostgresHelper.GetById<Employee>(id);
            txtFullname.Text = employee.fullname;
            txtAddress.Text = employee.address;
            txtPhone.Text = employee.phone;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnGetData_Click(null, null);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            var id = Convert.ToInt32(txtID.Text);
            var deleteEmployee = new Employee() { id = id };
            PostgresHelper.Delete(deleteEmployee);

            // refresh data to gridview
            btnGetData_Click(null, null);
        }
    }
}

Thanks for watching!

 

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn Thêm, xóa, sửa với PostgreSQL winform
Đăng bởi: Thảo Meo - Lượt xem: 2082 14:34:27, 08/06/2023C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.