'프로그래밍/ADO.NET'에 해당되는 글 8건

제목 날짜
  • 배우자 찾기 2012.05.01
  • winform 속성으로 DB 연결 2012.04.06
  • Winform도서관 2012.04.06
  • Winform 디비 연결(3) 2012.04.05
  • 연결 지향(전화), 비연결 지향, DataSet 2012.04.05
  • 명령 객체 재사용, 다중 결과셋 처리, 단일 결과셋 처리 2012.04.05
  • Parameters 2번째, SELECT, reader + command 2012.04.04
  • Connection, Command, INSERT, UPDATE, ExcuteNonQuery, 프로시져 연결, Parameters 2012.04.04

배우자 찾기













































저작자표시

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

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 today

{

       public partial class Form1 : Form

       {

             public Form1()

             {

                    InitializeComponent();

             }

 

             private void Form1_Load(object sender, EventArgs e)

             {

                    con.Open();//db접속

                    SelectAll();

             }

 

             //모든 레코드를 가져와서 리스트뷰에 출력하기

             public void SelectAll()

             {

                    //기존에 있던 리스트는 초기화 -> 새로운 항목으로..

                    listView1.Items.Clear();

                   

 

                    SqlDataReader reader = cmdSelectAll.ExecuteReader();

 

                    //레코드 -> ListViewItem 생성

                    while (reader.Read())

                    {

                           ListViewItem item = new ListViewItem(reader["seq"].ToString());

 

                           item.SubItems.Add(reader["name"].ToString());

                           item.SubItems.Add(reader["regDate"].ToString());

 

                           DateTime regDate = (DateTime)reader["regDate"];

 

                           item.SubItems.Add(regDate.ToLongDateString());

 

                           listView1.Items.Add(item);

                    }

                   

                    reader.Close();

             }

 

             private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)

             {

                    //한명을 선택 -> View 띄우기

                    string seq = listView1.SelectedItems[0].Text;

                    //this.Text = seq;

 

                    Ex07_view view = new Ex07_view();

                    view.StartPosition = FormStartPosition.CenterParent;

                    view.Seq = seq;//**부모와 대화 프로퍼티에게 현재 seq를 반환

                    view.Owner = this;

                    view.ShowDialog();

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    Ex07_add add = new Ex07_add();

                    add.StartPosition = FormStartPosition.CenterParent;

                    add.Owner = this;//내가 니부모다. 추가시키는 창한테 부모창을 건네준다.

                    add.ShowDialog();

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    //검색하기

                    //1. 어느 컬럼?

                    //2. 검색어?

                    string serchText = textBox1.Text.Trim();

 

                    string searchColumn = "";

 

                    switch (comboBox1.SelectedItem.ToString())

                    {

                           case "번호":

                                 searchColumn = "seq";

                                 break;

                           case "이름":

                                 searchColumn = "name";

                                 break;

                           case "주소":

                                 searchColumn = "address";

                                 break;

                           case "나이":

                                 searchColumn = "age";

                                 break;

                    }

 

                    cmdSearch.CommandText = string.Format("SELECT seq, name, regDate FROM tblAddress WHERE {0} LIKE '%{1}%';", searchColumn, serchText.Replace("'", "''"));

 

                    //리스트 출력

                    SqlDataReader reader = cmdSearch.ExecuteReader();

 

                    //이전에 리스트 -> 초기화

                    listView1.Items.Clear();

 

                    while (reader.Read())

                    {

                           ListViewItem item = new ListViewItem(reader["seq"].ToString());

                           item.SubItems.Add(reader["name"].ToString());

 

                           DateTime regData = (DateTime)reader["regDate"];

                           item.SubItems.Add(regData.ToLongDateString());

 

                           listView1.Items.Add(item);

                    }

 

                    reader.Close();

             }

 

             private void button3_Click(object sender, EventArgs e)

             {

                    SelectAll();

             }

 

             private void Form1_FormClosed(object sender, FormClosedEventArgs e)

             {

                    con.Close();

             }

       }

}



추가 




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 today

{

       public partial class Ex07_add : Form

       {

             public Ex07_add()

             {

                    InitializeComponent();

             }

 

             private void Ex07_add_Load(object sender, EventArgs e)

             {

                    for (int i = 10; i < 50; i++)

                    {

                           comboBoxAge.Items.Add(i.ToString());

                    }

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //추가하기

                    con.Open();

 

                    //매개변수값 대입

                    cmdInsert.Parameters["@name"].Value = textBoxName.Text;

                    cmdInsert.Parameters["@age"].Value = comboBoxAge.SelectedItem.ToString();

                    cmdInsert.Parameters["@email"].Value = textBoxEmail.Text;

                    cmdInsert.Parameters["@address"].Value = textBoxAddress.Text;

                    cmdInsert.Parameters["@tel"].Value = textBoxTel.Text;

 

                    cmdInsert.ExecuteNonQuery();//반환값이 없는 INSERT 이니

 

                    con.Close();

 

                    //창닫기

                    this.Close();

 

                    //부모가 가지는 SelectAll() 호출(리스트 갱신)

                    ((Form1)this.Owner).SelectAll();

             }

 

             private void Ex07_add_FormClosed(object sender, FormClosedEventArgs e)

             {

                    con.Close();

             }

       }

}

 

 

수정 삭제 조회







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 today

{

       public partial class Ex07_view : Form

       {

 

             private string seq;//자신이 보여야할 회원번호

 

             public string Seq//프로퍼티

             {

                    set { this.seq = value; }

             }

 

             public Ex07_view()

             {

                    InitializeComponent();

             }

 

             private void Ex07_view_MouseDoubleClick(object sender, MouseEventArgs e)

             {

                    //한명을 선택 -> View 띄우기

             }

 

             private void Ex07_view_Load(object sender, EventArgs e)

             {

                    //콤보박스 초기화

                    for (int i = 10; i <= 50; i++)

                    {

                           comboBoxAge.Items.Add(i.ToString());

                    }

 

                    //부모가 건네준 회원번호를 조건으로 모든 컬럼값을 Select -> 컨트롤 출력

                    con.Open();

 

                    cmdSelectOne.Parameters["@seq"].Value = seq;

 

                    SqlDataReader reader = cmdSelectOne.ExecuteReader();

 

                    if (reader.Read())

                    {

                           labelSeq.Text = reader["seq"].ToString();

                           textBoxName.Text = reader["name"].ToString();

                           comboBoxAge.SelectedItem = reader["age"].ToString();

                           textBoxEmail.Text = reader["email"].ToString();

                           textBoxTel.Text = reader["tel"].ToString();

                           textBoxAddress.Text = reader["address"].ToString();

                           labelRegDate.Text = reader["regDate"].ToString();

 

                    }

 

                    reader.Close();

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //수정하기 DB는 열려 있는 상태

                    cmdUpdate.Parameters["@name"].Value = textBoxName.Text;

                    cmdUpdate.Parameters["@age"].Value = comboBoxAge.SelectedItem.ToString();

                    cmdUpdate.Parameters["@email"].Value = textBoxEmail.Text;

                    cmdUpdate.Parameters["@address"].Value = textBoxAddress.Text;

                    cmdUpdate.Parameters["@tel"].Value = textBoxTel.Text;

                    cmdUpdate.Parameters["@seq"].Value = seq;//이미 부모단에서 넘겨주었다. seq스번호를

 

                    cmdUpdate.ExecuteNonQuery();

                   

                    //창닫기 -> 리스트 갱신

                    this.Close();

 

                    ((Form1)this.Owner).SelectAll();

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    //삭제하기

                    if (MessageBox.Show("정말 삭제하시겠습니까", "삭제확인", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)

                    {

                           //cmdDelete

                           cmdDelete.Parameters["@seq"].Value = seq;

 

                           cmdDelete.ExecuteNonQuery();

 

                           this.Close();

 

                           ((Form1)this.Owner).SelectAll();

                    }

             }

       }

}

 

DataGridView

수정 삭제 조회를 컨트롤러가 자동으로 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;

 

namespace today

{

       public partial class Ex09_DataGridview : Form

       {

             public Ex09_DataGridview()

             {

                    InitializeComponent();

             }

 

             private void Ex09_DataGridview_Load(object sender, EventArgs e)

             {

                    sqlDataAdapter1.Fill(dataSet11.tblAddress);//데이터를 채워놓는다.

 

                    //데이터 바인딩

                    // - WPF(속성 <-> 속성)

                    // - Winform

                    // - ASP.NET

                    //공식적으로 데이터 바인딩 지원

 

                    //데이타 베이스에 제약사항을 모두 지켜준다.

                    dataGridView1.DataSource = dataSet11.tblAddress;

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //1. DataGridView는 오로지 데이터바인딩을 통해서만 데이터를 추가시킬 수 있음.(Items.Add() - 없음)

                    //2. DataGridView에서 데이터를 편집하게 되면 DataGridView의 DataSource에 설정된 DataSet의 데이터가 변경이 된다.

                    MessageBox.Show(dataSet11.tblAddress.Rows[0]["age"].ToString());

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    //데이터베이스 서버에 반영시키기

                    //DataGridView에서 편집한 데이터를 실제 DB에 적용

                    //DataGridView로 편집해서 수정이된 DataSet을 소유하고 있는 DataAdapter가 반영 담당 객체

                    sqlDataAdapter1.Update(dataSet11.tblAddress);

             }

       }

}

 












 

저작자표시

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

Winform도서관





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;

using System.Data.SqlClient;

 

namespace WInform

{

       public partial class ex05 : Form

       {

             public ex05()

             {

                    InitializeComponent();

             }

 

             private void ex05_Load(object sender, EventArgs e)

             {

                    //전체 목록 -> ListView에 추가

                    con.Open();

 

                    SqlDataReader reader = cmdSelect.ExecuteReader();//전체 레코드를 가져옴

 

                    while (reader.Read())

                    {

                           //테이블의 레코드 1개 -> ListView의 Item 1개

                          ListViewItem item = new ListViewItem(reader["title_id"].ToString());

 

                           item.SubItems.Add(reader["title"].ToString());

 

                           listView1.Items.Add(item);

                    }

 

                    reader.Close();

 

             }

 

             private void ex05_FormClosed(object sender, FormClosedEventArgs e)

             {

                    //DB 종료

                    con.Close();

             }

 

             private void listView1_SelectedIndexChanged(object sender, EventArgs e)

             {

                    //책중에 1권을 선택 -> 상세보기

                    // 2 -> 4

                    // 2 -> -1 -> 4 (리스트뷰 속성의 특징)

                    if (listView1.SelectedItems.Count > 0)//필수로 이 if를 넣어주어야 한다.

                    {

                           string title_id = listView1.SelectedItems[0].Text;

 

                           //MessageBox.Show(title_id);

                          

                           //조건부 셀렉트 -> cmdSelectOne

                           cmdSelectOne.Parameters["@title_id"].Value = title_id;//조건 완료

                          

                           //실행

                           SqlDataReader reader = cmdSelectOne.ExecuteReader();

 

 

                           if (reader.Read())

                           {

                                 //reader -> 선택한 책에 커서를 위치

                                 labelTitle.Text = reader["title"].ToString();

                                 labelTitleID.Text = reader["title_id"].ToString();

                                 labelType.Text = reader["type"].ToString();

                                 labelPrice.Text = string.Format("${0:N2}", float.Parse(reader["가격"].ToString()));

                                 labelPubdate.Text = ((DateTime)reader["pubDate"]).ToShortDateString();

                                 richTextBox1.Text = reader["notes"].ToString();

 

                                 //책표지

                                 Bitmap img = new Bitmap(@"images\Title-" + reader["title_id"].ToString() + ".gif");

                                 pictureBox1.Image = img;

                           }

 

                           reader.Close();

 

                    }

             }

       }

}

 

 


저작자표시

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

Winform 디비 연결


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;

using System.Data.SqlClient;

 

namespace WInform

{

       public partial class Form1 : Form

       {

             private SqlConnection con;

 

             public Form1()

             {

                    InitializeComponent();

                    con = new SqlConnection("server=localhost;database=ADONET;uid=sa;pwd=net401$!"); ;

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    if (con.State != ConnectionState.Open)

                    {

                           con.Open();

                           this.Text = con.State.ToString();

                    }

             }

             private void Form1_Load(object sender, EventArgs e)

             {

                    this.Text = con.State.ToString();

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    con.Close();

                    this.Text = con.State.ToString();

             }

 

             private void button3_Click(object sender, EventArgs e)

             {

                    this.Close();

             }

       }

}

  

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;

using System.Data.SqlClient;

 

namespace WInform

{

       public partial class Connection : Form

       {

             private SqlConnection con;

 

             public Connection()

             {

                    InitializeComponent();

                    con = new SqlConnection("server=localhost;database=ADONET;uid=sa;pwd=net401$!"); ;

             }

 

             private void Connection_Load(object sender, EventArgs e)

             {

                    //로드 할때 open(); 버튼을 누를때마다 open(); 차이가 있다.

                    //로드 : 계속 연결상태 버튼 : 누를때 마다.

                    //위 2항목은 모두 DB에게 무리가 간다.

                    //장기적으로 연결해야 한다면 로드나 다른 이벤트에서 OPEN 하도록 하는것이 좋다.

                    con.Open();

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //추가하기

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "INSERT INTO tblMelon(title, singer) VALUES(@title, @singer)";

 

                    cmd.Parameters.Add(new SqlParameter("@title", SqlDbType.VarChar, 100));

                    cmd.Parameters.Add(new SqlParameter("@singer", SqlDbType.VarChar, 100));

 

                    cmd.Parameters["@title"].Value = textBox1.Text;

                    cmd.Parameters["@singer"].Value = textBox2.Text;

 

                    cmd.ExecuteNonQuery();

 

                    con.Close();

 

                    textBox1.Text = textBox2.Text = "";

                    MessageBox.Show("데이타 추가가 완료 되었습니다.");

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    this.Close();

             }

 

            

       }

}





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;

using System.Data.SqlClient;

 

namespace WInform

{

       public partial class Select : Form

       {

             public Select()

             {

                    InitializeComponent();

             }

 

             private void Select_Load(object sender, EventArgs e)

             {

                    //1. 연결 객체 생성 - 완료

                    //2. 연결 문자열 - 완료

                    //3. 연결

                    sqlConnection1.Open();

 

                    //4. 명령 객체 생성 - 완료

                    //5. 명령 - 연결 짝 - 완료

                    //6. 명령 CommendText

                    //7. 실행

                    SqlDataReader reader = sqlCommand1.ExecuteReader();

 

                    while (reader.Read())

                    {

                           comboBox1.Items.Add(reader["title"].ToString());

                    }

 

                    if (reader.NextResult())

                    {

                           if (reader.Read())

                           {

                                this.Text += " - 도서 권수 : " + reader[0].ToString() + "권";

                           }

                    }

 

                    reader.Close();

                    sqlConnection1.Close();

             }

       }

}

 

 

 



 1. 도구상자 항목 선택에서 코넥션, 커맨드, 어댑터 항목 추가


2. 코넥션 디자인에서 던져서 속성창에서











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;

using System.Data.SqlClient;

 

namespace WInform

{

       public partial class SELECT02 : Form

       {

             public SELECT02()

             {

                    InitializeComponent();

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    sqlConnection1.Open();

 

                    //입력 매개변수 처리

                    sqlCommand1.Parameters["@name"].Value = textBox1.Text;

                    sqlCommand1.Parameters["@age"].Value = textBox2.Text;

                    sqlCommand1.Parameters["@email"].Value = textBox3.Text;

                    sqlCommand1.Parameters["@address"].Value = textBox4.Text;

                    sqlCommand1.Parameters["@tel"].Value = textBox5.Text;

 

                    sqlCommand1.ExecuteNonQuery();

 

                    sqlConnection1.Close();

             }

       }

}

 

 

>                     this.Text = con.State.ToString();

             }

 

             private void button3_Click(object sender, EventArgs e)

             {

                    this.Close();

             }

       }

}



 

 


저작자표시
  • 다섯공기
    2012.06.25 13:57

    웹호스팅은 www.teamjang.com 이 저렴하니 참고하세요~

  • 익명
    2019.10.27 21:19

    비밀댓글입니다

    • Favicon of https://zzarungna.com BlogIcon zzarungna
      2019.10.29 16:27 신고

      조금이라도 도움이 되었다니 다행입니다.!! :)

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

연결 지향(전화), 비연결 지향, DataSet

ADO.NET(DB자체는 동시성이라는 문제점을 항상 있다)

1. 연결지향(전화)

 - Connection

 - Command

 - DataReader

- DataAdapter(연결정보 + 결과셋 +  테이블 + 컬럼 + 레코드 정보를 가지고 있다.)


2. 비연결 지향 ( 동시성을 버리고서라도 속도면에서 엄청난 이득이 있어서 비연결 지향을 쓴다)

 - DataSet(비중이 굉장히 높다!!!)

어뎁터라는 속성으로 디비에 접근해서 결과셋을 데이터베이스에 얻어 메모리에 적재한다.

응용 프로그램이 죽으면 메모리에 있는 영역에 결과셋이기 때문에 사라진다.

속도 상으로 디비에 접근하여 연결지향적으로 접근하면 속도가 느리지만 , 비연결 지향으로 접근할때는 메모리에서 값을 얻어오는 것이기 때문에 속도면에서 차이가 엄청난다.


 - 실데이터가 삭제되거나 업데이트가 된경우 DataSet에 메모리에 상주 된것은 동기화 되어있지 않은 상태이므로 단점이 생긴다.

 - 처음에 가져온 데이터를 보는 용도로만 사용한다.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

       class EX16_DataSet

       {

             static void Main(string[] args)

             {

                    string query = "SELECT * FROM tblAddress";

 

                    //1. 어댑터 생성 = 연결객체(SqlConnection) + 명령객체(SqlCommand)

                    // query : SqlCommand 담당이었다.

                    // ADONET : sqlConnection

                    // SqlDataAdapter : 내부적으로 커넥션 객체가 하나 만들어지고, 커맨드 객체도 하나만들어진다. 2개의 객체를 감싸주는 컨테이너이다.

                    // - 눈에 안보이게 캡슐화 되어 있는 상태이다.

                   

                    //2. 데이터셋 생성(복사되어진 결과셋을 저장할 로컬의 메모리 공간) = 로컬 DB(SQL SERVER의 데이터베이스와 같음)

                    SqlDataAdapter adapter = new SqlDataAdapter(query, Settings1.Default.ADONET);

 

                    //데이터베이스 = 테이블 집합(컬럼집합 + 레코드집합) = DataSet

                    DataSet ds = new DataSet();

 

                    //3. 복사!!

                    // - adapter 통해서 ds에 데이터를 채워넣기

                    //복사명령 db접근, 쿼리문 실행, 데이터결과셋 생성, 결과값 ds에 저장 모든게 캡슐화 되어있다.

                    // DB 접속중이지 않다.

                    adapter.Fill(ds);//메소드 안에서만 DB 접속중

                    // DB 접속중이지 않다.

 

                    //4. 가져온 데이터를 사용(주목적!!!!!!!)

                    // - DB와의 연결은 끊긴 상태 *****************비연결 지향

 

                    //DataSet의 구조

                    // - DataTable의 집합 : 테이블

                    // - DataRow의 집합 : 레코드

                    // - DataColumn : 컬럼

 

                    //현재 로컬DB인 ds안에는 테이블 1개가 있습니다.

                    Console.WriteLine(ds.Tables.Count);

 

                    //ds안의 테이블 접근 방법

                    //1. 이름으로 접근

                    //2. 인덱스로 접근

                    //ds.Tables["tblAddress"] //X

                    //c#에서 만든 테이블은 이름을 새로 지정해 주어야 한다.

                    ds.Tables[0].TableName = "tblAddress";//원본이름과 같은 형태로 주는것이 좋다.

                    //이름을 주고 난뒤에 이름으로 접근 가능!!

                    DataTable tblAddress = ds.Tables["tblAddress"];

 

                    //DataTable내의 데이터 접근

                    //tblAddress.Rows : 행(레코드)의집합

                    for (int i = 0; i < tblAddress.Rows.Count; i++)

                    {

                           DataRow row = tblAddress.Rows[i];//한행

 

                           //이론상 경제적이고 속도가 엄청 빠르다.

                           Console.WriteLine(row["name"].ToString());

                           Console.WriteLine(row["age"].ToString());

                    }

 

                    //컬렉션 <-> SqlDataReader

                    //4번째 레코드의 전화번호 바로접근 가능!!!

                    Console.WriteLine(tblAddress.Rows[3]["tel"].ToString());

             }

       }

}

 

 


 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

       class Ex17_DataSet

       {

             static void Main(string[] args)

             {

                    //DB -> 테이블 n개

                    //DataSet -> DataTable n개

                    M1();

             }

 

             private static void M1()

             {

                    //1. 어뎁터

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "SELECT * FROM tblAddress";

 

                    //원래 adapter가 알아서 코넥하고 커맨드하는데 현재 예제는 응용하기 위해서 직접넣어주었다.

                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

 

                    //2. 데이터셋

                    DataSet ds = new DataSet();

 

                    //3. 채워넣기

                    //이름을 같이 한번에 넣어주자

                    adapter.Fill(ds, "tblAddress");

                    Console.WriteLine(ds.Tables.Count);

 

                    //4. 또 다른 결과셋을 가져오기 멜론 테이블 접근

                    // cmd(con) -> adapter소속

                    cmd.CommandText = "SELECT * FROM tblMelon";

 

                    //5. 채워넣기(횟수에 상관없이 계속 채워넣기가 가능하다)

                    adapter.Fill(ds, "tblMelon");

                    Console.WriteLine(ds.Tables.Count);

 

                    //- 되도록 여러개의 테이블은 채워넣지 않도록 한다 -> c# 동장죽인 컴퓨터의 메몰 -> 테이블이 많아지면 -> 메모리 부족..

 

                    //6. 탐색

                    for (int i = 0; i < ds.Tables["tblAddress"].Rows.Count; i++)

                    {

                           Console.WriteLine(ds.Tables["tblAddress"].Rows[i]["name"].ToString());

                    }

 

                    foreach (DataRow row in ds.Tables["tblMelon"].Rows)

                    {

                           Console.WriteLine(row["singer"].ToString());

                    }

             }

       }

}

 

 

 

저작자표시

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

명령 객체 재사용, 다중 결과셋 처리, 단일 결과셋 처리



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

namespace AdoConsole

{

       class Ex13

       {

             static void Main(string[] args)

             {

                    //1. 반환값이 없는 쿼리 : ExecuteNonQuery()

                    //2. 반환값이 있는 쿼리 : ExecuteReader()

                    //  -> SqlDataReader의 사용법

                    M1();//***필수(단점 코딩이 길다) / 장점 가독성이 높다.

                    //M2();//응용

                    //M3();//응용 최적화

             }

 

             private static void M3()

             {

                    //매니저 먼트에서 하는 행동은 c#에서 모두 가능하다.

                    //명령 객체를 재사용

                    // - 1개의 명령 객체를 가지고 여러개의 SQL 실행

 

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    con.Open();//연결

 

                    //매개변수 값이 다를때는 같은 매개변수 이름으로 주어서는 안된다.

                    //매개변수 값이 같다면 커멘드 객체를 하나만 만들도록 한다.

                    SqlCommand cmd1 = new SqlCommand();

                    cmd1.Connection = con;

                    cmd1.CommandText = "INSERT INTO tblAddress (name, age, email, address, tel) VALUES (@name, @age, @email, @address, @tel); UPDATE tblAddress SET age = @age2 WHERE seq = @seq;";

 

                    //매개변수 구성 따로 했던 작업을 하나의 작업으로 갯수 7개에 맞춰 만든다.

                    cmd1.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 10));

                    cmd1.Parameters.Add(new SqlParameter("@age", SqlDbType.Int));//Int 생성자 오버로딩이 자동으로 되어있다.

                    cmd1.Parameters.Add(new SqlParameter("@age2", SqlDbType.Int));//Int 생성자 오버로딩이 자동으로 되어있다.

                    cmd1.Parameters.Add(new SqlParameter("@email", SqlDbType.VarChar, 50));

                   cmd1.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar, 200));

                    cmd1.Parameters.Add(new SqlParameter("@tel", SqlDbType.VarChar, 15));

                    cmd1.Parameters.Add(new SqlParameter("@seq", SqlDbType.Int));

 

                    cmd1.Parameters["@name"].Value = "가가가";//인덱서가 키값으로 사용할수 있게 만들어 놓았다.

                    cmd1.Parameters["@age"].Value = 20;

                    cmd1.Parameters["@age2"].Value = 99;

                    cmd1.Parameters["@seq"].Value = 9;

                    cmd1.Parameters["@email"].Value = "ga@ga.com";

                    cmd1.Parameters["@address"].Value = "서울시";

                    cmd1.Parameters["@tel"].Value = "010-14454-4545";

 

                    cmd1.ExecuteNonQuery();//실행

 

                    con.Close();//닫기

             }

 

             private static void M2()

             {

                    //명령 객체를 재사용

                    // - 1개의 명령 객체를 가지고 여러개의 SQL 실행

 

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    con.Open();//연결

 

                    SqlCommand cmd1 = new SqlCommand();

                    cmd1.Connection = con;

                    cmd1.CommandText = "INSERT INTO tblAddress (name, age, email, address, tel) VALUES (@name, @age, @email, @address, @tel);";

 

                    //매개변수 구성

                    cmd1.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 10));

                    cmd1.Parameters.Add(new SqlParameter("@age", SqlDbType.Int));//Int 생성자 오버로딩이 자동으로 되어있다.

                    cmd1.Parameters.Add(new SqlParameter("@email", SqlDbType.VarChar, 50));

                   cmd1.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar, 200));

                    cmd1.Parameters.Add(new SqlParameter("@tel", SqlDbType.VarChar, 15));

 

                    cmd1.Parameters["@name"].Value = "가가가";//인덱서가 키값으로 사용할수 있게 만들어 놓았다.

                    cmd1.Parameters["@age"].Value = 20;

                    cmd1.Parameters["@email"].Value = "ga@ga.com";

                    cmd1.Parameters["@address"].Value = "서울시";

                    cmd1.Parameters["@tel"].Value = "010-14454-4545";

 

                    cmd1.ExecuteNonQuery();

 

                    cmd1.Parameters.Remove(cmd1.Parameters["@name"]);

                    cmd1.Parameters.Remove(cmd1.Parameters["@email"]);

                    cmd1.Parameters.Remove(cmd1.Parameters["@address"]);

                    cmd1.Parameters.Remove(cmd1.Parameters["@tel"]);

 

 

                    //SqlCommand 재사용

                    //UPDATE 실행

                    // - 명령 객체를 재사용할때는 매개변수가 구성이 어떻게 되어있는지 확인해야 한다.

                    // 많은 매개 변수를 보유하고 있어도 남는것은 컴파일시 무시한다.

                    //총 6개의 매개변수가 있다.

                    cmd1.CommandText = "UPDATE tblAddress SET age = @age WHERE seq = @seq";

 

                    //cmd1.Parameters.Add(new SqlParameter("@age", SqlDbType.Int)); 이미 위 구문에서 만들어 놓았기 떄문에 삭제~

                    cmd1.Parameters.Add(new SqlParameter("@seq", SqlDbType.Int));

 

                    cmd1.Parameters["@age"].Value = 100;

                    cmd1.Parameters["@seq"].Value = 5;

 

                    cmd1.ExecuteNonQuery();

 

                    con.Close();//닫기

             }

 

             private static void M1()

             {

                    //명령 객체를 재사용

                    // - 1개의 명령 객체를 가지고 여러개의 SQL 실행

 

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    con.Open();//연결

 

                    SqlCommand cmd1 = new SqlCommand();

                    cmd1.Connection = con;

                    cmd1.CommandText = "INSERT INTO tblAddress (name, age, email, address, tel) VALUES (@name, @age, @email, @address, @tel);";

 

                    //매개변수 구성

                    cmd1.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 10));

                    cmd1.Parameters.Add(new SqlParameter("@age", SqlDbType.Int));//Int 생성자 오버로딩이 자동으로 되어있다.

                    cmd1.Parameters.Add(new SqlParameter("@email", SqlDbType.VarChar, 50));

                   cmd1.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar, 200));

                    cmd1.Parameters.Add(new SqlParameter("@tel", SqlDbType.VarChar, 15));

 

                    cmd1.Parameters["@name"].Value = "가가가";//인덱서가 키값으로 사용할수 있게 만들어 놓았다.

                    cmd1.Parameters["@age"].Value = 20;

                    cmd1.Parameters["@email"].Value = "ga@ga.com";

                    cmd1.Parameters["@address"].Value = "서울시";

                    cmd1.Parameters["@tel"].Value = "010-14454-4545";

 

                    cmd1.ExecuteNonQuery();

 

                   //2. Update 실행 : SQL쿼리가 같은 디비를 바라 본다면 기존에 있던것을 사용, DB가 다른곳에 있다면 커넥션 객체 다시 생성

 

                    //SqlConnection은 1개를 가지고 사용

                    // - database당 1개의 SqlConnection 사용

 

                    //SqlCommand은 재사용?

                    //A. 재사용 안함

                    // - 추가로 생성(SqlCommand 재생성)

                    SqlCommand cmd2 = new SqlCommand();

                    cmd2.Connection = con;//하나의 커넥션은 2개의 커맨드를 연결 할수 있다.

                    cmd2.CommandText = "UPDATE tblAddress SET age = @age WHERE seq = @seq";

 

                    cmd2.Parameters.Add(new SqlParameter("@age", SqlDbType.Int));

                    cmd2.Parameters.Add(new SqlParameter("@seq", SqlDbType.Int));

 

                    cmd2.Parameters["@age"].Value = 100;

                    cmd2.Parameters["@seq"].Value = 5;

 

                    cmd2.ExecuteNonQuery();

 

                    con.Close();//닫기

             }

       }

}

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

       class Ex14_Select

       {

             static void Main(string[] args)

             {

                    //다중 결과셋 처리

                    // - SELECT의 결과가 2개 이상의 테이블 반환

                    // - 동시에 2개이상의 SELECT를 실행 SQL에서 SELECT * FROM tblAddress; SELECT * FROM tblAddress; 와 같은 효과

 

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "SELECT TOP 5 * FROM tblAddress ORDER BY regDate DESC; SELECT TOP 10 * FROM tblMelon";

 

                    //1개의 SELECT, 2개의 SELECT .. n개의 SELECT 가능

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    //다중 결과셋의 reader의 동작

                    // - 처음엔 첫번쨰 결과셋을 대상으로 움직임 와일이 끝까지 돌아도 첫번째 결과만 리턴한다.

                    // - 다음 결과셋으로 이동하는 명령(그다음 테이블..)

                    // - 다음 결과셋을 대상으로 움직이면 된다.

 

                    while (reader.Read())

                    {

                           Console.WriteLine(reader[1].ToString());

                    }

 

                    //그 다음 결과 셋으로 이동(tblMelon)

 

                    //이러한 형태로 반드시 한다..

                    if (reader.NextResult())

                    {

                           while (reader.Read())

                    {

                           Console.WriteLine(reader[1].ToString());

                    }

                    }

                   

 

                   

 

                    con.Close();

             }

       }

}

 

 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

       class Ex15_Select

       {

             static void Main(string[] args)

             {

                    //SQL 명령을 실행합니다. 문구

                    //ExcuteNonQuery() : 반환값 X

                    //ExcuteReader() : 반환값 O SELECT

                    //ExcuteScalar() : ? SELECT(반환값이 있는 쿼리르 처리하는것)

                    //M1();

                    M2();

             }

 

             private static void M2()

             {

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

 

                    //아래 쿼리 공통점 반환값이 1개인 경우 인쿼리

                    //SELECT max(age) FROM tblAddress;

                    //SELECT name FROM tblAddress WHERE age = (SELECT MAX(age) FROM tblAddress);

 

                    cmd.CommandText = "SELECT max(age) AS name FROM tblAddress;";

 

                    //SELECT 실행 스칼라는 첫번째 데이터를 직접 반환한다. 결과 테이블에 첫번쨰행 첫번쨰데이타 반환

                    int result = (int)cmd.ExecuteScalar();

 

                    //값이 하나였을때만 가능한 메소드다 스칼라는 단일!!!!!!!!!!!!!!

                    Console.WriteLine("{0}세 최고 어르신", result.ToString());

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    //while (reader.Read())

                    //{

                    //반환값이 2개이상 일때

                    //}

 

                    con.Close();

             }

 

             private static void M1()

             {

 

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONET);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

 

                    //아래 쿼리 공통점 반환값이 1개인 경우 인쿼리

                    //SELECT max(age) FROM tblAddress;

                    //SELECT name FROM tblAddress WHERE age = (SELECT MAX(age) FROM tblAddress);

 

                    cmd.CommandText = "SELECT max(age) AS name FROM tblAddress;";

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    if (reader.Read())//다음칸으로 이동했는데 있으면 진행 없으면 진행 안함

                    {

                           Console.WriteLine("{0}세 최고 어르신", reader["name"].ToString());

                    }

 

 

                    //while (reader.Read())

                    //{

                    //반환값이 2개이상 일때

                    //}

 

                    con.Close();

             }

       }

}

 

 


 

저작자표시

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

Parameters 2번째, SELECT, reader + command




using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

           class Parametesr02

           {

                     static void Main(string[] args)

                     {

                                //매개변수가 있는 프로시저 호출

                                // - upTblAddresInsert2

                               

                                //1. 연결

                                SqlConnection con = new SqlConnection(Settings1.Default.ADONETConStr);

                                con.Open();

 

                                //2. 명령

                                SqlCommand cmd = new SqlCommand();

                                cmd.Connection = con;

                                cmd.CommandText = "upTblAddressInsert2";

                                cmd.CommandType = CommandType.StoredProcedure;

 

                                //3. 매개변수 구성 - 프로시저내의 매개변수와 연결을 하기 위해서...

                                cmd.Parameters.Add("@name", SqlDbType.NVarChar, 10);

                                cmd.Parameters.Add("@age", SqlDbType.Int);

                                cmd.Parameters.Add("@email", SqlDbType.NVarChar, 50);

                                cmd.Parameters.Add("@address", SqlDbType.NVarChar, 200);

                                cmd.Parameters.Add("@tel", SqlDbType.NVarChar, 15);

 

                                //SqlParameter 사용하는 이유 ?

                                // - 기본적인 예외처리를 알아서 해줌..

                                // - 대부분의 컨트롤과 마법사에서 SQL에 대한 매개변수를 SqlParameter로 취급

                                // Parametes는 기본적인 예외처리를 알아서 처리해준다.

                                cmd.Parameters["@name"].Value = "하하하하하하하하하하하하하하하하하하하";

                                cmd.Parameters["@age"].Value = 20;

                                cmd.Parameters["@email"].Value = "hi.naver.com";

                                cmd.Parameters["@address"].Value = "부산서울'ㄴ'ㅇㅇㅇ";

                                cmd.Parameters["@tel"].Value = "012-345-6789";

 

                                cmd.ExecuteNonQuery();

 

                                con.Close();

                     }

           }

}





using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

       class Select

       {

             static void Main(string[] args)

             {

                    //연결 -> 질의 -> 결과셋(ResultSet) 처리 -> 종료

                    //반환값이 있는 질의

                    // - 단순, 서브쿼리, 조인, 함수, 유니온,

 

                    M1();

                    //M2();

                    //M3();

                    //M4();

                    //M5();

             }

 

             private static void M5()

             {

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONETConStr);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "SELECT * FROM tblAddress";

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    while (reader.Read())

                    {

                           //가독성이 떨어져서 첫번째 주석단 것을 대부분 사용한다.

 

                           //내부적으론 인티져 이지만 오브젝트로 형변환되서 값이 넘어온다.

                           //오브젝트형은 가장 상위 계층이기 때문에 하위 계층으로 형변환이 대부분 다된다.

                           //int age = (int)reader["age"];//object -> int

                           int age = reader.GetInt32(2);//index밖에 못쓰지만 자동으로 형변환 해준다. 위에 방법이나 아래방법으로 편한방법으로 사용 하도록 한다.

                           age -= 10;

 

                           //

                           //DateTime regDate = (DateTime)reader["regDate"]; //object -> DateTime

                           DateTime regDate = reader.GetDateTime(6);//6번째 컬럼값을 자동으로 형변환 해준다. 메소드자체 기능에 추가 되있음.

                           TimeSpan span = DateTime.Now - regDate;

 

                           Console.WriteLine("{0}님 - {1}세 이고 - {2}시간쨰" ,reader["name"].ToString(), age, regDate);

                    }

 

                    reader.Close();

                    con.Close();

             }

 

             private static void M4()

             {

                    //SqlDataReader 접근하는 레코드셋은 원본이 아니라 결과 셋이다~!

                    SqlConnection con = new SqlConnection(Settings1.Default.SQLExConStr);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    //결과셋이기 때문에 질의한 쿼리문에서 결과 셋으로 나온 네임으로 출력을 해주어야 한다.

                    cmd.CommandText = "SELECT name, popu AS [인구수] FROM tblCountry";

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    //반복문 반환값이 TRUE , FALSE 이기 때문에 while문이 가장 적합하다.

                    while (reader.Read())

                    {

                           //n번째 레코드를 커서가 위치..

                           Console.WriteLine("{0} - {1}", reader["name"].ToString(), reader["인구수"].ToString());

                    }

                    reader.Close();

                    con.Close();

 

             }

 

 

             private static void M3()

             {

                    SqlConnection con = new SqlConnection(Settings1.Default.SQLExConStr);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "SELECT * FROM tblCountry";

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    //반복문 반환값이 TRUE , FALSE 이기 때문에 while문이 가장 적합하다.

                    while (reader.Read())

                    {

                           //n번째 레코드를 커서가 위치..

                           Console.WriteLine("{0} - {1}", reader ["name"].ToString(), reader["capital"].ToString());

                    }

                    reader.Close();

                    con.Close();

             }

 

             private static void M2()

             {

                    SqlConnection con = new SqlConnection(Settings1.Default.SQLExConStr);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "SELECT * FROM tblCountry";

 

                    //실행

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    reader.Read();//true(데이터있다.), false(없다)

 

                    Console.WriteLine(reader["name"].ToString());

                    Console.WriteLine(reader["capital"].ToString());

 

                    reader.Read();

                    //마지막 구문까지 읽어 들였을때는 데이터가 없는데 name을 달라고 할경우 에러가 난다.

                    con.Close();

             }

 

             private static void M1()

             {

                    SqlConnection con = new SqlConnection(Settings1.Default.ADONETConStr);

                    con.Open();

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "SELECT * FROM tblAddress";

 

                    //SELECT 실행

                    //reader : 판독기

                    // - SQL에서 변환한 결과셋을 레코드 단위로 접근 후 원하는 컬럼의 값을 가져오는 역할

                    //MS SQL은 결과셋을 반환한다 C#한테 얻어진 결과셋을 reader가 관리한다.

                    //reader 객체 커서를 아래한칸으로 내린다. 순차적으로 커서를 내리면서 원하는 컬럼값을 찾아와야 한다.

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    //커서를 결과셋의 첫번째 레코드로 이동하시오.

                    reader.Read();

 

                    //현재 커서가 위치한 레코드의 원하는 컬럼값을 읽기

                    Console.WriteLine(reader["name"].ToString());

                    Console.WriteLine(reader["age"].ToString());

                    Console.WriteLine(reader["email"].ToString());

                    Console.WriteLine(reader["address"].ToString());

                    Console.WriteLine(reader["tel"].ToString());

 

                    Console.WriteLine(reader[2].ToString());

 

                    reader.Read();

                    Console.WriteLine(reader["name"].ToString());

 

                    reader.Read();

                    Console.WriteLine(reader["name"].ToString());

                    reader.Read();

                    Console.WriteLine(reader["name"].ToString());

                    reader.Read();

                    Console.WriteLine(reader["name"].ToString());

                    reader.Read();

                    Console.WriteLine(reader["name"].ToString());

                    reader.Close();

                    con.Close();

             }

 

       }

}

 

 


 

 

저작자표시

트랙백

※ 스팸 트랙백 차단중 ...{ ? }

Connection, Command, INSERT, UPDATE, ExcuteNonQuery, 프로시져 연결, Parameters

1. 코넥션, 커맨드 짝지어주기, 쿼리문 스트링형태로 전달




using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

//ADO.NET 관련 클래스

using System.Data;//DB의 종류에 상관없이 일반적인 DB작업 관련 클래스

using System.Data.SqlClient;//MS-SQL(여러버전) 2000이상, MS-SQL Data Provider

using System.Data.OleDb;//OLEDB Data Provider Oracle 접근 가능

using System.Data.Odbc;//ODBC Data Provider Oracle 접근 가능

//--oracle.com -> 오라클 전용 Provider를 제공한다. 설치하면 된다. 오라클 버젼별로 만들어 주어야 한다.

namespace AdoConsole

{

        class Connection

        {

               static void Main(string[] args)

               {

                       //사람 -> SSMS -> SQL -> 질의실행 -> DB -> 결과

                       //응용프로그램 -> C# -> SQL -> 질의실행 -> DB -> 결과

                       //데이타베이스 서버는 SQL만 받는다.

 

                       //SQL 사용하는 절차(사람)

                       //1. SSMS 실행

                       //2. 연결(서버, 계정명, 암호)

                       //3. 데이터베이스 선택

                       //4. SQL 작성

                       //5. SQL 실행

                       //6. 결과

                       //7. 연결종료

 

                       //SQL 사용하는 절차(C#)

                       //1. SSMS -> C#프로그램을 통해서(ADO.NET 클래스)

                       //2. 연결

                       SqlConnection con = new SqlConnection();

                       //OdbcConnection con1;

                       //OleDbConnection con2;

                       //OracleConnection con3;

 

                       // - 연결 문자열(DB에 접속하기 위해서 알아야 하는 정보)

                       //   - 서버주소, 계정, 암호, 데이터베이스

                       // DB는 항상 try catch를 염두해 둔다.

                       //server 주소가 틀리거나 서버가 꺼져있을경우

                       con.ConnectionString = "server=localhost; database=ADONET; uid=sa2; pwd=net401$!";//연결 문자열

 

                       Console.WriteLine(con.State);//State 열거형 속성 연결상태

 

                       // - 연결

                       con.Open();//예외 발생 가능성이 있다.

 

                       Console.WriteLine(con.State);//State 열거형 속성 연결상태

 

                       //4.5.6 진행...

 

                       //7. 연결 종료

                       con.Close();

 

                       Console.WriteLine(con.State);//State 열거형 속성 연결상태

               }

        }

}

 





using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

        class insert

        {

               static void Main(string[] args)

               {

                       //tblAddress에 레코드 추가

                      

                       //1. DB연결

                       SqlConnection con = new SqlConnection();

                       con.ConnectionString = "server=localhost;database=ADONET;uid=sa;pwd=net401$!";

                       con.Open();

 

                       if (con.State == ConnectionState.Open)

                       {

                              //2. Insert

                              //2.1 명령객체 생성

                              // - 모든 SQL 구문을 실행

                              // - 명령은 1회 이상 가능

                              // - 동일한 SQL을 여러번 반복 O

                              // - SQL을 바꿔서 다시 실행O

                              SqlCommand cmd = new SqlCommand();

 

                              //2.2 명령객체에게 연결객체 소개(필수!!)

                              //커맨드객체는 코넥션을 가지고 있어야한다.

                              cmd.Connection = con;

 

                              //2.3 실행할 SQL 작성

                             cmd.CommandText = @"INSERT INTO tblAddress (name, age, email, [address], tel)

                                                                    VALUES ('홍길동', 20, 'hong@test.com', '서울시', '010-5555-6666');";

 

                              //2.4 SQL 실행

                              //2.4.1 반환값이 없는 질의(나머지)

                              //2.4.2 반환값이 있는 질의(select)

                              Console.WriteLine("현재 인서트된 갯수는 {0}건 입니다.",cmd.ExecuteNonQuery());

                       }

 

                       con.Close();

               }

        }

}



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

        class input

        {

               static void Main(string[] args)

               {

                       //tblAddress에 레코드 추가

 

                       //1. DB연결

                       SqlConnection con = new SqlConnection();

                       con.ConnectionString = "server=localhost;database=ADONET;uid=sa;pwd=net401$!";

                       con.Open();

 

                       if (con.State == ConnectionState.Open)

                       {

                              SqlCommand cmd = new SqlCommand();

 

                              //2.2 명령객체에게 연결객체 소개(필수!!)

                              //커맨드객체는 코넥션을 가지고 있어야한다.

                              cmd.Connection = con;

 

                              //2.3 실행할 SQL 작성

                      

                              //사전 작업 - 사용자로부터 데이터 입력

                              //SQL의 자료형과 C#의 자료형은 아무 상관이 없다.

                              Console.Write("이름 : ");//nvarchar(10)

                              string name = Console.ReadLine();

 

                              Console.Write("나이 : ");//int

                              string age = Console.ReadLine();

 

                              Console.Write("이메일 : ");//nvarchar(50)

                              string email = Console.ReadLine();

 

                              Console.Write("주소 : ");//nvarchar(200)

                              string address = Console.ReadLine();

 

                              Console.Write("전화번호 : ");//nvarchar(15);

                              string tel = Console.ReadLine();

 

                              //예외처리 (호따옴표 하나를 호따옴표 두개로 바꾸려면 (' -> '')

                              name = name.Replace("'", "''");

                              age = age.Replace("'", "''");

                              email = email.Replace("'", "''");

                              address = address.Replace("'", "''");

                              tel = tel.Replace("'", "''");

 

 

                              //cmd.CommandText = @"INSERT INTO tblAddress (name, age, email, [address], tel)  VALUES ('"+name+"', '"+age+"', '"+email+"', '"+address+"', '"+tel+"');";

                              cmd.CommandText = string.Format(@"insert into tblAddress (name, age, email, [address], tel) values ('{0}', {1}, '{2}', '{3}', '{4}');", name, age, email, address, tel);

                              //위에 구문중 하나가 빠지게 되면 쿼리 에러가 난다.

                              //디버깅용 확인용

                              Console.WriteLine(cmd.CommandText);

                              Console.ReadLine();

                              Console.WriteLine("현재 인서트된 갯수는 {0}건 입니다.", cmd.ExecuteNonQuery());

                       }

 

                       con.Close();

               }

        }

}






using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

using System.Data;

using System.Data.SqlClient;

 

 

namespace AdoConsole

{

        class Update

        {

               static void Main(string[] args)

               {

                       //반환값이 없는 쿼리 : ExecuteNonQuery()

 

                       //회원 번호 입력 -> 주소를 변경

                       //UPDATE tblAddress SET

                       //address = '주소'

                       //WHERE  seq = 5;

 

                       //1. 연결작업

                       SqlConnection con = new SqlConnection();

                       con.ConnectionString = Settings1.Default.ADONETConStr;

                       con.Open();

 

                       //2. 어느 회원?

                       Console.Write("수정할 회원 번호 : ");

                       string seq = Console.ReadLine();

 

                       Console.Write("수정할 주소 : ");

                       string address = Console.ReadLine();

 

                       //3. 명령 객체

                       SqlCommand cmd = new SqlCommand();

                       cmd.Connection = con;

                      

                       string query = string.Format(@"UPDATE tblAddress SET [address] = '{0}' WHERE seq = {1}", address, seq);

                       cmd.CommandText = query;//실제 쿼리문 날리기~

 

                       //4. 실행

                       int result = cmd.ExecuteNonQuery();

                       if (result == 1)

                              Console.WriteLine("수정되었습니다.");

                       else

                              Console.WriteLine("수정되지 않았습니다.");

 

                       //5. dusruf whdfy

                       con.Close();

               }

        }

}

 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

using System.Data;

using System.Data.SqlClient;

 

namespace AdoConsole

{

        class Delete

        {

               static void Main(string[] args)

               {

                       //회원번호를 입력 -> 회원 삭제

 

                       //1. 번호 입력

                       Console.Write("삭제할 회원 번호 : ");

                       string seq = Console.ReadLine();

 

                       //2. 연결 객체

                       SqlConnection con = new SqlConnection(Settings1.Default.ADONETConStr);

                       con.Open();

 

                       //3. 질의문

                       string query = "delete from tblAddress where seq = " + seq;

 

                       //4. 명령