블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
반응형

Category

Recent Post

Recent Comment

Archive

2009. 10. 1. 14:40 .Net Project/ADO.NET 3.5
반응형

 




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Linq;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            ToDoListDataContext context = new ToDoListDataContext();
            Table<Items> items = context.GetTable<Items>();

            var q = from item in items select item;

            foreach (var desc in items)
         {
          listBox1.Items.Add(desc.Description + "," + desc.Priority);
         }

            //저장 프로시저 ??
            //.점 찍으면 업데이트,삭제 모두 노출되었다

            this.dataGridView1.DataSource = context.GetItems();        
        }
    }
}






반응형
posted by Magic_kit
2009. 10. 1. 09:17 .Net Project/ADO.NET 3.5
반응형
- 오늘 / 앞으로 해야할 일 목록을 나열
- 기록일 / 완료일
- 우선순위 결정 

- ToDoList  SQL 쿼리문 작성



Create Table Items
(
 ID Int Identity(1,1) Primary Key, --일련번호
 Description VarChar(8000) Not Null, --설명
 Opened DateTime Default(GetDate()), --등록일
 Closed DateTime Null, --완료일
 Priority TinyInt Default(1) --우선순위(1:높음, 2:보통, 3:낮음)
)
Go
--[1] 6가지 예시문 : 입력, 출력, 상세, 수정, 삭제, 검색
--ToDo
--입력

Insert Into Items Values('안녕하세요',GETDATE(),GETDATE(),'1')
Insert Into Items Values('시간 어때요?',GETDATE(),GETDATE(),'2')
Insert Into Items Values('감사 합니다',GETDATE(),GETDATE(),'3')

--출력
Select *From Items Order by Description Asc

--상세
Select *From Items Where Description='안녕하세요'

--수정
Begin Tran
 Update Items
   Set Description = '반갑습니다' Where Description = '안녕하세요'
 
--RollBack Tran
Commit Tran


--삭제
Begin Tran
 Delete Items
 Where 1 = 1
 --RollBack Tran
Commit Tran

--검색  
Select *From Items
   Where Description Like '%하%'
Go

--[2] 6가지 저장 프로시저
--입력 저장 프로시저

Create Proc dbo.AddItem
    @Description VarChar(8000),
    @Priority TinyInt
As
   Insert Into Items(Description, Priority) Values(@Description, @Priority)
Go

--출력 저장 프로시저
Create Proc dbo.GetItems
As
   Select *From Items Order by ID Asc
Go

--상세 저장 프로시저
Create Proc dbo.GetItem
   @ID Int
As
   Select *From Items Where ID = @ID
Go

--수정 저장 프로시저
Create  Proc dbo.UpdateItem
   @Description VarChar(8000),
   @Opened DateTime,
   @Closed DateTime,
   @Priority TinyInt,
   @ID Int
As
 Update Items Set Description = @Description, Opened = @Opened,
       
Closed=@Closed, Priority=@Priority Where ID = @ID
Go

--삭제  저장 프로시저
Create Proc dbo.DeleteItem
   @ID Int
As
 Delete Items Where ID = @ID
Go

--검색 저장 프로시저 
Create Proc dbo.GetItemsByDescription
   @SearchQuery VarChar(25)
 
As
 Declare @str VarChar(500)
 Set @str = '
 Select *From Items Where Description Like ''%%' + @SearchQuery + '%''
 '
Exec(@str) 
Go

--예시 데이터 입력
Exec AddItem '오늘은 ToDoList를 만들자',1
Exec AddItem '오늘은 ToDoList를 분석하자',2


- ToList WinForm에서 DB불러오기


 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

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


        private DataSet ds; //데이터셋
        private SqlDataAdapter da; //데이터 어댑터
        private DataTable dt;

        private void btnUpdate_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection
              ("server=.;database=ToDoList;uid=ToDoList;pwd=1234;");

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;

            cmd.CommandText = "Select *From Items";
            cmd.CommandType = CommandType.Text;

            da = new SqlDataAdapter(cmd);

            ds = new DataSet();

            da.Fill(ds, "Items");

            dt = ds.Tables[0];

            //2가지 방법을 사용하여 출력하는 방법으로 표현 
            //this.ctlToDoList.DataSource = ds.Tables[0].DefaultView;
              this.ctlToDoList.DataSource = dt;
        }
    }
}


-- 입력/수정/삭제 추가 부분

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        private DataSet ds; //데이터셋
        private SqlDataAdapter da; //데이터 어댑터
        private DataTable dt;

        private void btnUpdate_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection
             ("server=.;database=ToDoList;uid=ToDoList;pwd=1234;");
           

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;

            cmd.CommandText = "Select *From Items";
            cmd.CommandType = CommandType.Text;

            da = new SqlDataAdapter
            ("Select *From Items",con); //SelectCommand

            //InsertCommand
            cmd = new SqlCommand();//아..객체생성..
            cmd.Connection = con;
            cmd.CommandText = "AddItem";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add
                  ("@Description", SqlDbType.VarChar, 8000, "Description");
            cmd.Parameters.Add
                  ("@Priority", SqlDbType.TinyInt, 8, "Priority");
           
            //UpdateCommand
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "UpdateItem";
            cmd.CommandType = CommandType.StoredProcedure;
           
            cmd.Parameters.Add
            ("@Description", SqlDbType.VarChar, 8000, "Description");
           
            cmd.Parameters.Add
            ("@Priority", SqlDbType.TinyInt, 8, "Priority");
           
             cmd.Parameters.Add
             ("@Opened", SqlDbType.DateTime, 32, "Opened");
           
            cmd.Parameters.Add
            ("@Closed", SqlDbType.DateTime, 32, "Closed");
           
            cmd.Parameters.Add("@ID", SqlDbType.Int, 32, "ID");
            da.UpdateCommand = cmd;

            //DeleteCommand
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "DeleteItem";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@ID", SqlDbType.DateTime, 10, "ID");
            da.DeleteCommand = cmd;

            ds = new DataSet();

            da.Fill(ds, "Items");

            dt = ds.Tables[0];

            //this.ctlToDoList.DataSource = ds.Tables[0].DefaultView;
            this.ctlToDoList.DataSource = dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            da.Update(dt); //업데이트
        }
    }
}








 

반응형
posted by Magic_kit
2009. 9. 30. 16:40 .Net Project/ADO.NET 3.5
반응형

 

LINQ To SQL 
- 관계형 데이터를 개체로 관리하는 런타임 인프라를 제공합니다.
- Linq To Sql에서 관계형 데이터베이스의 데이터 모델은 개발자의 프로그래밍 언어로 표현
  된 개체 모델로 매핑 됩니다. 
- 응용 프로그램을 실행하면 Linq to SQL에서는 개체 모델의 언어 통합 쿼리를 SQL로 변환
  하여 실행을 위해 데이터베이스로 전송합니다. 
- 데이터베이스에서는 결과를 반환하면 Linq to SQL에서 해당 결과를 사용자가 조작 가능 

Program.Cs
---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Linq;
using System.Data.Linq.Mapping;

namespace WinLinqToSQL
{
    /// <summary>
    /// Addressbook 테이블과 일대일 매칭되는 클래스 생성 
    /// </summary>
    //Table 특성을 사용해서 테이블로 보자
    [Table(Name="AddressBook")] 
    class AddressBook
    {
        private int _Num;
        [Column(IsPrimaryKey=true, Storage="_Num")]
        public int Num   //Num속성은 Num컬럼과 매칭, 기본키 설정
        {
            get { return _Num;}
            set {_Num = value;}
       }
----------------------------------------------------------------------
        private string _Name;
        [Column(IsPrimaryKey = true, Storage = "_Name")]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
----------------------------------------------------------------------
        private string _Mobile;
        [Column(IsPrimaryKey = true, Storage = "_Mobile")]
        public string Mobile
        {
            get { return _Mobile; }
            set { _Mobile = value; }
        }
----------------------------------------------------------------------------
        private string _Email;
        [Column(IsPrimaryKey = true, Storage = "_Email")]
        public string Email
        {
            get { return _Email; }
            set { _Email = value; }
        }

    }
}

 WinLinqToSQL.Form
----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Linq;

namespace WinLinqToSQL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            //초기화자
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Display(); //함수호출
        }

        private void Display()
        {
            // 출력
            // Linq to SQL방법으로 Table과 동일한 구조의
            // Entity 클래스가 만들어졌다면..
            // [1]
            DataContext context = new DataContext

DataContext : CLR(공용 언어 런타임) 개체의 속성인 바인딩을
                   사용하여 해당 개체 직접 설정 가능

XAML에서 Binding선언으로 설정되며, 속성 요소 구문이나
특성 구문을 사용 가능 합니다.

그리고, 코드에서 DataContext 설정 할 수 도 있습니다.
  
("server=.;database=AddressBook;uid=AddressBook;pwd=1234;");

     //[2] Context의 GetTable<T> 팩터리 메서드로 테이블 매핑해서 가져오기 
          Table<AddressBook> addr = context.GetTable<AddressBook>();

            //[3] LINQ Query 날리기
            var q = from a in addr
                    select a;
           
            //[4]출력
            foreach (var item in q)
            {
                listBox1.Items.Add(item.Name + "," + item.Mobile);
            }
        }
    }
}









반응형
posted by Magic_kit
2009. 9. 30. 16:08 .Net Project/ADO.NET 3.5
반응형

 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WinLinqDataSet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection
          
         ("server=.;database=AddressBook;uid=AddressBook;pwd=1234;");
            con.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select *From AddressBook";

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;

            DataSet ds = new DataSet();
            da.Fill(ds, "AddressBook");

       //LINQ를 사용해서 Listbox에 아이템 추가해보자

- DataSet을 사용하면 다른 많은 데이터 소스에서 사용 할 수 있는
  동일 한 쿼리 기능을 사용하여 보다 풍부한 쿼리 기능을 DataSet에
  빌드 가능

-  Linq to Dataset 사용하면 DataSet 개체에 캐시된 데이터를 쉽고
    빠르게 쿼리 가능하며, 특히 Linq to DataSet을 사용하면 별도의
    쿼리 언어를 사용하는 대신 프로그래밍 언어 자체에서 쿼리를 작성
    할 수 있으므로 간편하게 쿼리 가능합니다.

       var q = ds.Tables[0].AsEnumerable(); //DataTable을 Linq 타입
       //이름 순으로 정렬(가,나,다,라 순으로)
       var addr = from ad in q orderby ad.Field<string>("Name")
                      select ad;

            foreach (var item in addr)
            {
                listBox1.Items.Add(item.ItemArray[1] + ","
                + item.ItemArray[2] + "," + item.ItemArray[3]);
            }
              con.Close();
        }
    }
}

            //DataSet반복
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                listBox2.Items.Add(dt.Rows[i]["Name"]
                            + "," + dt.Rows[i]["Mobile"]);
            }


            //DataReader로 출력
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string s = dr["Name"].ToString() + "," + dr.GetString(2);
                listBox3.Items.Add(s);
            }
            con.Close();






반응형
posted by Magic_kit