AdoNet

AdoNet veritabanı ile programımız arasında köprü görevi gören CRUD (Create Read Update Delete) işlemlerimizi yapmamızı sağlayan bir teknolojidir.

Öncelikle bağlantı oluşturulmalı

SqlConnection connection = new SqlConnection(@"server=(localdb)\MSSQLLocalDB;initial catalog=ETrade;integrated security=true");

Sonrasında komut blokları yazılır

SELECT

        SqlConnection connection = new SqlConnection(@"server=(localdb)\MSSQLLocalDB;initial catalog=ETrade;integrated security=true");
        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }
        SqlCommand command = new SqlCommand("Select * from Products", connection);
        SqlDataReader reader = command.ExecuteReader();
        DataTable dataTable = new DataTable();
        dataTable.Load(reader);
        reader.Close();
        connection.Close();
        dgwProducts.DataSource=dataTable;

Fonksyonu bu şekilde DataTable tipinde yapabiliriz fakat günümüz kullanımında pek kalmadı. DataTable, Memory açısından pahallı bir nesnedir hem de kişiselleştirme özelliği yoktur.

Bunun yerine Databasedeki tablomuzun örn Products olsun, kodsal karşılığını tutan bir sınıf oluştururuz. örn Product.cs

Bu oluşturduğumuz sınıf Products tablosundaki kayıtları bir liste şeklinde tutmamızı sağlar

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdoNetDemo
{
    public class Product
    {
        //Products tablomuzun karşılığını Product class'ında aynen oluşturalım
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal UnitPrice { get; set; }
        public int StockAmount { get; set; }
    }
}

Prodcuts tablomuz için CRUD operasyonlarının yapıldığı ProductDal (Product Data Access Layer) isimli bir sınıf oluşturup operasyonları burada çağıralım

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdoNetDemo
{
    class ProductDal
    {
        /*
         * ProductDal : Product Data Access Layer
         * Bizim veritabanından veriyi çekme,ekleme,silme,güncelleme (CRUD) operasyonları içerir
         * Benim birde elimdek tablomun kodsal karşılığına ihtiyacımız var. 
         * Elimizdeki tablo Products her bir satırda bir Product tutuyor o zaman oluşturacağımız sınıf Product olacak
         * CRUD işlemlerini iki şekilde yapabiliriz, biri datatable döndürerek diğeri ise list döndürerek
         * DataTable döndürerek yapmak eski ve pahallı bir iştir memory'i kasar dinamiklik yoktur
         * List ise daha kullanışlı ve dinamiktir fakat bunun için tablodaki satırı tutan bir class oluşturmamız lazım (Tablo:Products ise Class:Product)
         * **/

        SqlConnection _connection = new SqlConnection(@"server=(localdb)\MSSQLLocalDB;initial catalog=ETrade;integrated security=true");
        // Ters slash (\) karakter atlamma anlamı vardır fakat biz ifadenin başına @ eklersek ifademizin tamamen string'ten oluştuğunu belirtiriz
        //integrated security=true ifadesi Veritabanımıza windows autotentication ile bağlan demek.Pcye login olduğumuz hesaplar SQL'i açabiliyorsak buna win aut deniyor
        //Uzaktakii bir veritabanına bağlanmak istersek: integrated security=false;uid=Mehmet;password=12345 şeklinde connection stringi düzenleriz

        //SELECT
        public List<Product> GetAll()
        {
            ConnectionControl();
            SqlCommand command = new SqlCommand("Select * from Products", _connection);
            //Sql serverla iletişim kurmak için SQL (Structured Query Language) dilini kullanırız. Örneğin bir tablodan veri çekmek ya da bir tabloya veri eklemek için.
            //Bu kodu çalıştırmak içinde adından da anlaşılacağı gibi SqlCommand yani SqlKomut sınıfından yararlanırız.Bu da bizden komutu ve connection'u parametre olarak ister.
            //Biz bu komutu oluşturduk ama çalıştırmamız lazım bunun için command.ExecutreReader kullanırız (Select yanii tablodan veri çekerken ExecuteReader kullanırız)
            //ExecuteReader() bize SqlDataReader dönderir. SqlDataReader class'ından bir nesne oluşturup gelen ifadeyi atarız(ref type old için aslında referanslarını eşitliyoruz)
            SqlDataReader reader = command.ExecuteReader();
            List<Product> products = new List<Product>();
            while (reader.Read()) //readerdaki tüm elemanları oku
            {
                Product product = new Product   //Her okunan elemanı product'a aktar
                {
                    Id = Convert.ToInt32(reader["Id"]),
                    Name = reader["Name"].ToString(),
                    StockAmount = Convert.ToInt32(reader["StockAmount"]),
                    UnitPrice = Convert.ToDecimal(reader["UnitPrice"])
                };
                products.Add(product);  //product'a aktarılan elamanları da listeye ekle

            }
            reader.Close();
            _connection.Close();
            return products;    //listeyi döndür

        }

        private void ConnectionControl()
        {
            //Biz connecton'u oluşturduk ama bunu çalıştırmamız gerekli bunun için connection.Open() kullanırız. 
            //Bir bağlantı açıkken yeni bir bağlantı hata vereceği için bunu if bloğuna alarak, bağlantı kapalıyken aç diyebiliriz
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }
        }

        // Fonksyonu DataTable tipinde de yapabiliriz fakat günümüz kullanımında pek yok.Memory açısından pahallı bir nesnedir hemde kişiselleştirme özelliği yoktur
        public DataTable GetAll2()
        {
            SqlConnection connection = new SqlConnection(@"server=(localdb)\MSSQLLocalDB;initial catalog=ETrade;integrated security=true");
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            SqlCommand command = new SqlCommand("Select * from Products", connection);
            SqlDataReader reader = command.ExecuteReader();
            DataTable dataTable = new DataTable();
            dataTable.Load(reader);
            reader.Close();
            connection.Close();
            return dataTable;
        }

        //INSERT
        public void Add(Product product)
        {
            ConnectionControl();
            SqlCommand command = new SqlCommand("Insert into Products values(@name,@unitPrice,@stockAmount)", _connection);
            command.Parameters.AddWithValue("@name", product.Name);
            command.Parameters.AddWithValue("@unitPrice", product.UnitPrice);
            command.Parameters.AddWithValue("@stockAmount", product.StockAmount);
            command.ExecuteNonQuery();
            _connection.Close();
        }

        //UPDATE
        public void Update(Product product)
        {
            ConnectionControl();
            SqlCommand command = new SqlCommand("Update Products set Name=@name, UnitPrice=@unitPrice, StockAmount=@stockAmount where Id=@id", _connection);
            command.Parameters.AddWithValue("@name", product.Name);
            command.Parameters.AddWithValue("@unitPrice", product.UnitPrice);
            command.Parameters.AddWithValue("@stockAmount", product.StockAmount);
            command.Parameters.AddWithValue("@id", product.Id);
            command.ExecuteNonQuery();
            _connection.Close();
        }

        //DELETE
        public void Delete(int id)
        {
            ConnectionControl();
            SqlCommand command = new SqlCommand("Delete from Products where Id=@id", _connection);
            command.Parameters.AddWithValue("@id", id);
            command.ExecuteNonQuery();
            _connection.Close();
        }
    }
}

CRUD operasyonlarımızı yazdık. Biz örnek uygulama olarak WinForm öğesini seçmiştik burada arayüz hazırlayıp ProductDal classımızdan ürün çağırma işlemlerini yazalım

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 AdoNetDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        ProductDal _productDal = new ProductDal();
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadProducts();
        }

        private void LoadProducts()
        {
            dgwProducts.DataSource = _productDal.GetAll();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            _productDal.Add(new Product
            {
                Name = tbxName.Text,
                UnitPrice = Convert.ToDecimal(tbxUnitPrice.Text),
                StockAmount = Convert.ToInt32(tbxStockAmount.Text)
            });
            LoadProducts();
            MessageBox.Show("Product added!");
        }

        private void dgwProducts_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            tbxNameUpdate.Text = dgwProducts.CurrentRow.Cells[1].Value.ToString();
            tbxUnitPriceUpdate.Text = dgwProducts.CurrentRow.Cells[2].Value.ToString();
            tbxStockAmountUpdate.Text = dgwProducts.CurrentRow.Cells[3].Value.ToString();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Product product = new Product
            {
                Id = Convert.ToInt32(dgwProducts.CurrentRow.Cells[0].Value),
                Name = tbxNameUpdate.Text,
                UnitPrice = Convert.ToDecimal(tbxUnitPriceUpdate.Text),
                StockAmount = Convert.ToInt32(tbxStockAmountUpdate.Text)
            };
            _productDal.Update(product);
            LoadProducts();
            MessageBox.Show("Updated!");
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(dgwProducts.CurrentRow.Cells[0].Value);
            _productDal.Delete(id);
            LoadProducts();
            MessageBox.Show("Deleted!");
        }
    }
}

Yorum bırakın

WordPress.com'da bir web sitesi veya blog oluşturun

Yukarı ↑

WordPress.com ile böyle bir site tasarlayın
Başlayın