Symbianize Forum

Most of our features and services are available only to members, so we encourage you to login or register a new account. Registration is free, fast and simple. You only need to provide a valid email. Being a member you'll gain access to all member forums and features, post a message to ask question or provide answer, and share or find resources related to mobile phones, tablets, computers, game consoles, and multimedia.

All that and more, so what are you waiting for, click the register button and join us now! Ito ang website na ginawa ng pinoy para sa pinoy!

BASICS: CRUD [Create/Retrieve/Update/Delete] - C# and MS SQL Server

lymcrest16

Professional
Advanced Member
Messages
158
Reaction score
0
Points
26
Hi! Sa mga gusto matuto ng basics sa C# at MS SQL Server
sa Pag-INSERT, EDIT, DELETE, RETRIEVE ng records sa database tama ang pinasukan niyo. Pero bago umusad sa CRUD may discuss muna ko :lol:


Requirements:
  • Brain
  • Visual Studio 2010 or higher
  • Microsoft SQL Server 2005 or higher

Ang gagamitin kong approach sa coding is yung 3 Layer Architecture.

First of all WHY 3 LAYER ARCHITECTURE?

Let's say meron kang isang Point-of-sale system na windows application na pinadevelop sa'yo ng isang company.
Karamihan kasi sa mga nagsisimulang magcode madalas gumagawa ng mga classes tapos sa loob ng classes andun lahat ng functions
e.g. Database connections, mga main functions sa system, etc. in short PINAGHALO-HALO lahat :lol:

Yes, sabihin natin na gumagana ng maayos ang system, pero paano kung sinabi ng client na gusto niya web-based na ang system?
Gagawa ka ba ulit ng mga bagong methods? Ida-dissect mo yung class mo at kukunin yung mga functions na gagamitin para sa web-based project?
Syempre hassle yun mga tol :slap:

Dito ngayon pumapasok ang role ni N-tier/3-tier Architecture.
Sa N-Tier Architecture most common is 3 layers talaga kaya tinawag na 3-Tier meron umaabot pa sa 4 or 5.
Pero focus tayo ngayon sa 3-Layer.


  • Presentation Layer/ UI Layer
    Alam niyo na siguro 'to. Ito yung Graphical User Interface. Dito nakikipag-interact yung mga end-user sa system.

  • Business Logic Layer
    Ito naman yung nasa taas ni Presentation Layer. Dito nakalagay halos lahat ng business operations sa system mo.
    Dito dadaan yung mga data na galing sa Presentation Layer.

  • Data Access Layer
    Ito naman yung nasa taas ng Business Layer. Ito yung nagsisilbing bridge ng Business Layer para makipag-interact sa database.
    Ito yung naglalaman ng mga methods para magperform ng CRUD operations sa database natin. Dito lahat ng database related stuffs mapupunta. :thumbsup:


Malinaw na ba? :lol:
Tara simulan na natin.

1. Create lang kayo ng new project.
C# Windows application dapat yung project niyo.
Pangalanan niyo ng kahit ano :yipee:

NOTE: 'Yung Form1 yan na yung presentation layer. Sabi ko nga kanina presentation layer yung user interface natin.


2. Mag-ADD kayo ng dalawang class file sa project.

Right click project > Add > Add new item .. or Class ..

'Yung unang class pangalanan niyong BL or BusinessLayer tapos 'yung isa DAL or DataAccessLayer bahala kayo kung ano gusto niyo malalaki na kayo :rofl:



Una muna nating i-code yung sa DataAccessLayer na class natin:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace CsharpDemo
{
    public class DAL
    {
        [COLOR="#008000"]//eto yung variable na sasalo ng mga error
        //importante kung nag-lolog ka sa system mo[/COLOR]
        public static string ErrorMessage { get; set; }

        public static DataTable dt = new DataTable();

        [COLOR="#008000"]//eto private string na lang din ..
        //basic pa lang naman dito na natin isetset yung connection string natin
        //set niyo kung ano connectionstring gagamitin niyo[/COLOR]
        private static string connectionString = string.Empty;

       [COLOR="#008000"] //Eto yung mga variable para sa mga database transactions
        //private na lang kasi dito lang naman gagamitin sa class na to[/COLOR]
        private static SqlConnection sqlConnection = null;
        private static SqlCommand sqlCommand = null;
        private static SqlDataAdapter sqlDataAdapter = null;
        private static SqlDataReader sqlDataReader = null;


       [COLOR="#008000"] //eto yung method na papasahan mo ng kahit anong select statement
        //tapos lahat ng marereturn na data ilalagay niya sa datatable
        //kaya nakalpublic yung declaration ng datatable natin sa taas
        //para accessible sa sa ibang class
        //bakit static? gusto ko lang haha para di na ko mag-instantiate ng bagong object nitong class na to
        //bakit boolean? mas madali ka para malalaman agad natin kung may mali sa ginawa natin[/COLOR]
        public static bool sqlQuery(string sqlstatement)
        {
            DataSet ds = new DataSet();
            try
            {
                using (sqlConnection = new SqlConnection(connectionString))
                {
                    sqlConnection.Open();
                    using (sqlCommand = new SqlCommand(sqlstatement, sqlConnection))
                    {
                        using (sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                        {
                            sqlDataAdapter.Fill(ds);
                            dt = ds.Tables[0];
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return false;
            }
            finally
            {
                sqlConnection.Close();
            }
        }
    }
}




NEW UPDATE !! :D

[RETRIEVING DATA FROM DATABASE]

Since meron na tayong Data Access Layer ..
Setup naman natin yung Business Logic Layer ..

eto yung code sa loob nung BLL class natin ..
[note: pinacreate ko kayo ng dalawa class files nung nagcreate tayo ng project]


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CsharpDemo
{
    public class BLL
    {
        [COLOR="#008000"]//setup tayo ng property ng class na sasalo sa error ng program :P[/COLOR]
        public string ErrorMessage { get; set; }
        

        [COLOR="#008000"]//eto may method tayong `display`
        //ito yung magpapasa ng query sa data access layer natin[/COLOR]
        public bool display()
        {
            [COLOR="#008000"]//ito yung query natin na ipapasa sa sqlQuery method natin sa data access layer na class[/COLOR]
            string query = @"select customernumber, 
                            dayspastdue, 
                            acct_name, 
                            balance, 
                            monthlyamortization 
                            from newendorsed";
            try
            {
                [COLOR="#008000"]//check if true yung condition natin 
                // yung `DAL` is yung name ng class natin for dataaccess layer
                //yung `sqlQuery()` naman is yung static boolean method natin na
                //magreretrieve ng records sa database magpapasa lang tayo ng query[/COLOR]
                if (DAL.sqlQuery(query))
                {
                    return true;
                }
                [COLOR="#008000"]//else ilalabas niya yung error message galing sa data access layer kapag false[/COLOR]
                else
                {
                    ErrorMessage = DAL.ErrorMessage;
                    return false;
                }
            }
            catch (Exception ex)
            {
                [COLOR="#008000"]//catch exception kung may error man na mangyari dito sa method na to :P[/COLOR]
                ErrorMessage = ex.Message;
                return false;
            }
        }
    }
}


dun naman tayo sa GUI naten :D
since may form na tayo .. mag-drag lang kayo ng isang button at isang datagridview ;)
ang name na ginamit ko sa datagridview ay dgvAccounts at yung button ay btnDisplay

NOW, double click niyo lang yung button tapos mapupunta kayo sa code-behind sa click event :P
bale ganito :)

Code:
private void btnDisplay_Click(object sender, EventArgs e)
        {
            [COLOR="#008000"]//create kayo ng instance ng class ng business logic layer natin
            //BLL ang binigay na pangalan ko para maikli :D[/COLOR]
            BLL bll = new BLL();

            [COLOR="#008000"]//check natin kung true yung condition para sa `display()` na method na ginawa natin[/COLOR]
            if (bll.display())
            {
                [COLOR="#008000"]//`dgvAccounts` yung name ng datagridview ko
                //kung true yung BLL syempre true din yung sa DAL
                //since true yung DAL may laman na yung datatable natin galing database[/COLOR]
                dgvAccounts.DataSource = DAL.dt.DataSet.Tables[0];
            }
            [COLOR="#008000"]//else? display nating yung error mga idol[/COLOR]
            else
            {
                MessageBox.Show("Error: " + bll.ErrorMessage, "System error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


kayo na bahala sa database niyo :rofl:

eto SS para maniwala kayong gumagana nga yan :lmao:

note: pag nag-ADD kayo ng datagridview wala na kayong gagalawin automatic na magkakaroon
ng column yun kapag na-bind sa datatable natin :thumbsup:


View attachment 179570


SANA TAMA YUNG GINAWA KO SA INTERFACE :rofl: puro console kasi ginagawa ko :lol:


sa susunod na yung iba ..
siningit ko lang to baka makatulong haha (sana) :rofl:



Post lang ng replies at violent reactions kung meron man para alam ko kung may mali sa ginawa ko salamat :salute:

 

Attachments

  • display.png
    display.png
    56.6 KB · Views: 171
Last edited:
salamat d2 boss.. sobrang laking tulong to! :clap:

question lang po: ung 3-Tier Architecture is parang "MVC" na din? or MVC cya, iba lng ung ginamit nyo na term?
 
Wow... Very Informative Sir.... Please keep this updated, now palang marami na akong natutunan hindi tulad ng sa school namin... Salamat ng marami Sir.
 
Good job TS! :salute:
ayos to para sa katulad ko na student palang :D
Subscribed na din.
 
Nalito ako sa instruction mo sir :)

Yung unang class pangalanan niyong BL or BusinessLayer tapos 'yung isa DAL or DataAccessLayer bahala kayo kung ano gusto niyo malalaki na kayo

Una muna nating i-code yung sa BusinessAccessLayer na class natin:
BAL? or DAL?

eto yung code sa loob nung BLL class natin ..

i-clear mo po yung instruction mo sa mga Newbie na KATULAD KO :lol:
 
Nalito ako sa instruction mo sir :)



BAL? or DAL?



i-clear mo po yung instruction mo sa mga Newbie na KATULAD KO :lol:


ay sorry :lol:
yung DAL is yung DataAccessLayer .. tapos yung BL or BLL yung business logic layer :rofl:
 
if you are using dataset always check if your dataset has a rows.. or else it gives you somewhere an object reference not set to an instance.
 
nice nice!! ang galing nito TS! may step by step procedure pa paano makakagawa! the best ito para sa mga baguhan saka dun na din para sa mga matatawag natin na spoon feed siyempre wala pa gaano alam pagdating sa C#.. sana mas marami pang tutorials na magawa TS!! :thanks: :10: :clap: :salute:


-----------------------------
EDIT

TS! matanong ko lang nga.. what if magrerestrict ng input sa textbox? halimbawa ang text box ay para sa age? paano marerestrict na numbers lang ang pwede input?
 
Last edited:
Wow astig nito! Best practice talaga si 3-tier Architecture TS! :clap:
 
nice nice!! ang galing nito TS! may step by step procedure pa paano makakagawa! the best ito para sa mga baguhan saka dun na din para sa mga matatawag natin na spoon feed siyempre wala pa gaano alam pagdating sa C#.. sana mas marami pang tutorials na magawa TS!! :thanks: :10: :clap: :salute:


-----------------------------
EDIT

TS! matanong ko lang nga.. what if magrerestrict ng input sa textbox? halimbawa ang text box ay para sa age? paano marerestrict na numbers lang ang pwede input?


Lagay mo sir sa keypress event ng textbox mo parang ganito :)


Code:
private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsLetter(e.KeyChar) ||
                char.IsSymbol(e.KeyChar) ||
                char.IsWhiteSpace(e.KeyChar) ||
                char.IsPunctuation(e.KeyChar))
            {
                e.Handled = true;
            }
        }
 
Salamat dito TS :praise: galing nito, meron akong natotunan dito... mas ma organized na yung program... salamat ts... :)

Hmmm... meron akong gustong malaman or gustong lang matutonan... ahmm... Panu magconnect sa remote database or sa ibang PC yung database using sql or mysql? puro local connection lang kasi database gamit ko. Pwede patulong TS? thnx.. :pray:
 
pa subscribe nga po dito TS. for future references lang :thanks:
 
Kelangan mo lang palitan yung server name ng IP address nung pc na kokonektahan mo sir
 
@TS

sana po magbigay ka din ng example ng simple log-in na may change password and validation :clap:
 
ts maganda toh..pa mark muna saka ko na pag aralan ng mabuti to kapag nakabili n ako ng laptop baka may kilala kang nagbibenta ng laptop pag programming lang salamt
 
wait lang mga idol ah magpost ako ng updates

medyo nabaon ako sa trabaho kaya natagalan :rofl:

upcoming updates:
-insert records to database
-update records
-delete records



:wave: :wave:
 
ts alam mu ba ang mvc
model
view cotrol?
tas entity framework
at linq?
 
Back
Top Bottom