블로그 이미지
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

Category

Recent Post

Recent Comment

Archive

2009. 9. 30. 15:30 .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 WinCommandBuilder
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private SqlDataAdapter da;
        private DataTable dt;

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

            SqlCommand cmd = new SqlCommand
                              ("Select *From AddressBook", con);

            da = new SqlDataAdapter(cmd);
            dt = new DataTable("Addressbook");

    //Select를 기준으로 Insert,Update,Delete문 자동 생성 :PK가 있어야 한다
            SqlCommandBuilder scb = new SqlCommandBuilder(da);

SqlCommandBuilder
- 연결된 SQL Server 데이터베이스에 Dataset의 변경 내용을
   조정하는 데 사용되는 단일 테이블 영향을 차등으로 생성
- 이 클래스는 상속 될 서 사용이 불가능

- public생성자에 의해 오버로드 되었습니다. SqlCommandBuiler
  클래스의 새 인스턴스를 초기화 하고 있습니다.

            da.Fill(dt); //채우기

            this.dataGridView1.DataSource = dt;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            da.Update(dt); //CRUD 실행
        }
    }
}




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

 

DataAdapter
- 데이터 소스에서 데이터를 검색하고 DataSet 내의 테이블을 채우는 데 사용
- DataAdapter은 DataSet에 대한 변경 내용을 다시 데이터 소스에 적용
- DataAdapter는 닷넷 프레임 워크 데이터 공급자의 Connection개체를 사용하여 
  데이터 소스에 연결하여 Command개체를 사용하여 데이터 소스에서 데이터를 검색하고
  변경 내용을 데이터 소스에 적용합니다. 

 


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.Configuration;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            Display(); //DataReader이용
            Display1(); //DataSet - Fill 이용
        }
        //Connection - command - DataReader - DataSet
        // DataTable 윈폼만... 패턴 출력

        private void Display()
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = 
           "server=.;database=AddressBook;uid=AddressBook;pwd=1234;";
            con.Open();
                       
            SqlCommand cmd = new SqlCommand
                              ("Select *From AddressBook", con);
            cmd.CommandType = CommandType.Text;

        SqlDataReader dr = cmd.ExecuteReader();//팩터리 메서드로 리더생성
            
        DataTable dt = new DataTable();
        dt.Load(dr);

            this.dataGridView1.DataSource = dt; //출력

            dr.Close();
            con.Close();
        }


        //Connection - Command - DataSet - Fill 패턴 출력
        private SqlDataAdapter da2;//필드레벨로 재선언
        private DataTable dt2;

        private void Display1()
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString =            
            server=.;database=AddressBook;uid=AddressBook;pwd=1234;";
            con.Open();

            SqlCommand cmd = new SqlCommand
                       
            da2 = new SqlDataAdapter(cmd);
            da2.SelectCommand = cmd;
            
      //삽입
      cmd = new SqlCommand
      ("Insert Into AddressBook Values
                      (@Name, @Mobile, @Email)", con);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar, 25, "Name");
        cmd.Parameters.Add
                              ("@Mobile",SqlDbType.VarChar, 25, "Mobile");
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 25, "Email");
       
        da2.InsertCommand = cmd;

            //수정
           cmd = new SqlCommand
            ("Update AddressBook Set
               Name = @Name,
Mobile=@Mobile,
               Email=@Email
Where Num = @Num", con);
           cmd.Parameters.Add
               ("@Name", SqlDbType.VarChar, 25, "Name");
           cmd.Parameters.Add
               ("@Mobile", SqlDbType.VarChar, 25,"Mobile");
           cmd.Parameters.Add
                  ("@Email", SqlDbType.VarChar, 25,"Email");
            cmd.Parameters.Add("@Num", SqlDbType.Int, 32, "Num");

            da2.UpdateCommand = cmd;
           
            //삭제
            cmd = new SqlCommand
                     ("Delete AddressBook Where Num = @Num",con);
            cmd.Parameters.Add("@Num",SqlDbType.Int,32,"Num");
            da2.DeleteCommand = cmd;
       
            dt2 = new DataTable("Addressbook");
            da2.Fill(dt2);
                                           
            this.dataGridView2.DataSource = dt2;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            da2.Update(dt2); //변경 내역 적용하기
        }
    }
}








반응형
posted by Magic_kit
2009. 9. 30. 12:20 .Net Project/ADO.NET 3.5
반응형
 DataConnection
- 개체에 액세스하려면 양식 서식 파일과 연결돤 DataConnectionCollection 개체를 사용
- DataConnectionCollection 개체에 액세스하려면 XMLForm 클래스의 DataConnection


 
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 ConnectionEvent
{
    public partial class Form1 : Form
    {
        //전역변수로 선언
        private SqlConnection con;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
     }

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new SqlConnection();
            con.ConnectionString =
                   "server=.;database=Market;uid=Market;pwd=1234;";
         
            con.StateChange += new
                  StateChangeEventHandler(con_StateChange);
            con.InfoMessage += new
                  SqlInfoMessageEventHandler(con_InfoMessage);
        }

 StateChange
- 이벤드는 이벤트 상태가 닫힘에서 열림으로 변경되거나 열림에서
  닫힘으로 변경되면 발생합니다.
- connection 상태가 바뀌면 StateChange 이벤트 발생하면 
  connection의 상태 변화를 확인할 수 있도록 
  StateChangeEvent를 받습니다
 InfoMessage
- 정보 메시지가 데이터 소스에서 반환시 발생하며,
  정보 메시지는 예외가 발생하지 않는 데이터 소스의 메시지 입니다.
- 데이터 소스에서 경고 및 정보 메싲를 검색 가능
- 데이터 소스에서 반환된 오휴의 심각도 수준이 11~16에 해당하면
  예외가 발생
- InfoMessage 이벤트 사용하여 캡쳐 될 수 있습니다

     void con_InfoMessage(object sender, SqlInfoMessageEventArgs e)
        {
            listBox1.Items.Add(e.Message);
        }

        void con_StateChange(object sender, StateChangeEventArgs e)
        {
            string Mes;
            Mes = string.Format("원래 상태 : {0}, 현재 상태 {1}",
                e.OriginalState, e.CurrentState);
            listBox1.Items.Add(Mes);
        }

        private void Form1_FormClosed
                                         (object sender, FormClosedEventArgs e)
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
    }
}








반응형
posted by Magic_kit
2009. 9. 30. 12:19 .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;
using System.Configuration;

namespace WinDataRelation
{
    public partial class Form1 : Form
    {
        private DataSet ds; //전역변수로 사용

        public Form1()
        {
            InitializeComponent();
        }

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

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText =
                     "Select CategoryID, CategoryName From Categories ";
            cmd.CommandType = CommandType.Text;

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

            ds = new DataSet();

            da.Fill(ds, "Categories");

            cmd.CommandText =
                  "Select ProductID, CategoryID, ModelName
                   From Products";
            da.SelectCommand = cmd;
            da.Fill(ds, "Products");

            //1번과 같은 방식을 사용할 경우, DB에서는 삭제 되지 않음
            //[1] Categories와 Products간에 관계설정(메모리상)
            //ds.Relations.Add(new DataRelation(
            //    "CP",
            //    ds.Tables[0].Columns["CategoryID"],
            //    ds.Tables[1].Columns["CategoryID"]));

            //[2]제약조건 걸기
            //부모 레코드 삭제시 자식이 참조하고 있으면 에러 

 ForeignKeyConstraint
- 값 또는 행이 삭제 되거나 업데이트될 때 기본키/외래키
   관계에서 열 집합에 적용되는 동작 제한 나타 냅니다.
- 기본키 열과 함께 사용되어야 하며, 두 테이블이
   부모/자식 관계
  에 있을 때 부모 테이블에서 값을 삭제하면 자식 행에
  다음 중
  한 가지 결과가 나타날 수 있습니다
  (자식 행이 삭제, 자식 열의 값이 Null 설정, 
          자식 열의 값이 기본값으로 설정, 예외 생성)

            ds.Tables["Products"].Constraints.Add(
                new ForeignKeyConstraint("PK_Pro",
                    ds.Tables[0].Columns["CategoryID"],
                    ds.Tables[1].Columns["CategoryID"]));

            //[3]삭제 규칙 적용
            ((ForeignKeyConstraint)
           ds.Tables[1].Constraints["PK_Pro"])
                .DeleteRule = Rule.None;
           
            this.dataGridView1.DataSource = ds.Tables[0];
            this.dataGridView2.DataSource = ds.Tables[1];
                       
            con.Close();

        }

WriteXml 
- XML 문서로 데이터만 쓰거나 데이터와 스키마를 사용 
- 데이터와 스키마를 모두 쓰려면 mode 매개 변수를 포함하는
  오버로드 중 하나를 사용하여 값을 WriteSchema 설정

ReadXml
- XML 스키마와 데이터를 DataTable 사용하여 읽어 올 수
   있습니다.

- XML 문서에서 DataSet으로 데이터만 또는 데이터와 스키마를
  모두 읽을 수 있으며, XMLReadMode 매개변수가 포함된
  ReadXML 오버로드 하나를 사용하고 해당 값을
  ReadSchema
  설정 가능 합니다.

- DataTable의 XML 데이터만 또는 스키와 데이터를
  모두 쓰려면, WriteXml 메서드 사용

- 스키마만 쓰려면 WriteXmlSchema메서드 사용 가능

        //XML로 저장하기
        private void button1_Click(object sender, EventArgs e)
        {
            ds.Tables[0].WriteXml
            ("C:\\Category.xml", XmlWriteMode.WriteSchema);
            MessageBox.Show("XML저장 완료");
        }

        //XML로 읽어오기
        private void button2_Click(object sender, EventArgs e)
        {
            DataTable read = new DataTable();
            read.ReadXml(@"C:\\Category.xml");

            this.dataGridView3.DataSource = read; //재바인딩
        }
    }
}







반응형
posted by Magic_kit