블로그 이미지
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 31
반응형

Category

Recent Post

Recent Comment

Archive

2009. 9. 30. 15:51 .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 Winbinding
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            //초기화자
            InitializeComponent();
        }

        private DataSet ds; //주수록 담을 그릇 (전역변수) 필드 선언
        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);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            ds = new DataSet();
            da.Fill(ds, "AddressBook"); //채우기

//[!]바인딩
//text1의 Text속성을  ds 에 담겨 있는 AddressBook 테이블의 Name필드 연결
 
         textBox1.DataBindings.Add("Text", ds, "AddressBook.Name");
         textBox2.DataBindings.Add("Text", ds, "AddressBook.Mobile");
         textBox3.DataBindings.Add("Text", ds, "AddressBook.Email");

        }
        //이전
        private void button1_Click(object sender, EventArgs e)
        {
           //감소
            BindingContext[ds, "AddressBook"].Position--; //레코드 이동

        }
        //다음
        private void button2_Click(object sender, EventArgs e)
        {
            //증가 
            BindingContext[ds, "AddressBook"].Position++; //다음 레코드
        }
    }
}









반응형
posted by Magic_kit
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
prev 1 2 3 4 5 ··· 7 next