반응형
using System;
using System.Collections.Generic;
using System.Text;
// C#에서 제공하는 기본 타입들 !! 
// 1) 값형 (data형)  : int, char.( 기본타입) 구조체, 열거형 
// 2) 참조형   :  pointer --> c/C++에서 포인터에 해당하는 변수들... 
//   heap메모리를 사용하는 변수인가??  !! 
// new 키워드를 통해 선언되어지는 변수들... class 


namespace 기본타입
{
    // 값형식--> stack, static . 참조형이 아니기때문에 필요없음 !!
    struct Student
    {
        public int StudentNo;
        public string StudentName; 
    }

    enum Color {  RED, GREEN, BLUE } 
    class Program
    {
        static void Main(string[] args)
        {
            // C#의 식별자 !! 

  /*          int Int; //? 
            int 911; 
            int 1num; 
            int Student-No;
            int @name; 
            int Student_name; 
            int @StudentNon; 
            */ 

            // 클래스이름 :  명사 
            // 인터페이스 :  명사 +  형용사 
            // 메소드 :  동사 
            // 변수 :  명사 
            // 파스칼 표기법을 기본으로 한다 !! 
          //  PascalNo;
          //  KonYang; 



            // 값형 
       /*     Color color; 
            color = (Color)1;
            Console.WriteLine( color.ToString() );

          // 값형타입 !! 
            //내장형 (기본타입) :  int, float 
            // 사용자 정의 : struct , enum
           // int, 
            Student s;
            s.StudentName = "홍길동";
            s.StudentNo = 1000;
            */
            // 박싱과 언박싱 ( boxing , unbox) 
            // 박싱 --> 값형식의 데이타를 참조형으로 변경 !! 
            // 스택에 저장된 값형의 데이타를 heap으로 이동시키는 작업 !! 
            int a = 10; // 스택 !! 
            //박싱 -->
            Object o = (Object)a;

            Console.WriteLine(o.ToString());
            // 언박싱 !! 
            int data = (int)o;

            Console.WriteLine(o.ToString());
            
            // 참조형 데이타 형식들... 
            //  class 
            //  인터페이스 
            //  델리게이트 
            //  배열 
            //  string  



        }
    }
}

'C#' 카테고리의 다른 글

[C#] 배열  (0) 2014.11.18
[C#] 델리게이트 (Delegate)  (0) 2014.11.18
[C#] C# 언어의 특징  (0) 2014.11.18
[C#] C# 객체 지향 프로그래밍!!  (0) 2014.11.18
[C#] Object 클래스란  (0) 2014.11.18
반응형
//**************************************************************************
// C#언어의 특징 !! 
//**************************************************************************
//  - .NET 플랫폼에 맞게 전용 언어 개발 !! 
//  - 간결한 문법 . 완전한 형태의 OOP를 지원 
//  - 언어적인 완성성되가 쵝오 !! /

//**************************************************************************
// include :  기존에 작성된 h파일을 포함 ( 불러서 사용하기위해) 
//**************************************************************************ㅋ
// namespace : 프로그램의 코드의 논리적인 영역을 나누기 위해 !! 
//**************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
// 추가된 네임스페이스 !!! 
using System.Windows.Forms; 
//************************************************************************** 
namespace 기본문법 // 기본 네임스페이스 !! 
{
//1) C#에서는 최소 1개 이상의 클래스들으로 구성  
    /// 
    ///   시작 클래스  
    /// 
    class Program
    {
        // 메인 함수는 static함수로 클래스 내부에 정의 되어야 한다 !!! 
        /// 
        ///  XML주석 !!  
        /// 
        ///  아규먼트
        static void Main(string[] args) // main함수가 클래스의 멤버 함수 !! 
        {
            Console.Write("Hello C#");
            string  str = Console.ReadLine();
            int key =    Console.Read();
            Console.WriteLine("asdasd");
        }
    }
}

'C#' 카테고리의 다른 글

[C#] 델리게이트 (Delegate)  (0) 2014.11.18
[C#] C#에서 제공하는 기본 타입들  (0) 2014.11.18
[C#] C# 객체 지향 프로그래밍!!  (0) 2014.11.18
[C#] Object 클래스란  (0) 2014.11.18
[C#] 메소드  (0) 2014.11.18
반응형
using System;
using System.Collections.Generic;
using System.Text;
//*****************************************************************************
//  C# 객체 지향 프로그래밍 !! 
//*****************************************************************************
//  객체 == 개체   :   행동과 속성 !! 
//  사물이나 개념 현상 등과 같은 유형무형의 정체성을 하나의 단위로 추상화하여 캡슐화한 것 !! 

//  -  추상화 :  시스템상에서 필요한 만큼의 부분을 추출하는것 !! 
// -   캡슐화 : 중요하고 세부적인 구형은 숨기고 인터페이스를 통해서 객체의를 핸들링 !! 
//       --> 데이타 은닉  --> 인터페이스를 통한 표준화되고 일관된 데이타 접근 !! 
//  - 상속 :   부모클래스로 부터 그대로 물려받는것 --> 상속 --> 구현상속 , 인터페이스 상속 !! 
//  - 다형성 : 같은 종류의 클래스가 하나의 메시지에 대해 서로 다른 행동을 하는것 !! 
// 추상화,캡슐화, 상속, 다형성 --->   OOP (  Object Oriented Programing) 


// 추상화와 캡슐화 !! 
//   ---> TV 
//  LCD , 스피커 ,  LED 등등 -->  리모컨 !!
//  리모컨 --> 

//캡슐화 !! 
// -->  필드(속성)  +  메서드(행동) 
//        접근 권한 ---> private public !! 
//        제한된 인터페이스를 통한 접근 및 사용 !1 


// 클래스 사이의 관계 !! 

//  종속 연관 !!! --->   집합 ,whole - part 관계  복합 !! 
//  일반화 --->  상속!! 
/*
                    자동차 
                        | 
        버스  택시  트럭  승용차 

 * 인터페이스와 인터페이스의 구현 !!  
 *    
 *    상수, 필드.           메소드, 프로퍼티 , 이벤트. 인덱서, 연산자 오버로딩, 생성자, 정적생성자  
 *    상속, 다형성, 추상클래스, 인터페이스  
 *    에리뷰트, 딜리게이트, 
 *       
 * 
 * 
 * 
 */



namespace OOP
{
       // C# 클래스 !! 
    // 문법 !! 
    class BitClass
    {
        private string name; //  필드  -> 멤버변수 !! 

        public string getName() { return name; } // 메소드 --->멤버 함수 !!
    }
    // 1) 인스턴스 멤버 
        // --> 객체마다 하나씩 생성이 되는 멤버     
    // 2) 정적 멤버  
       // --> 정적 멤버 클래스당 하나씩 생성되는 멤버 
        // -->같은 클래스로부터 생성된 객체들이 공유해서 사용하는 벱버 
       // --> static  
    class BitStudent
    {
        // 인스턴스 멤버 
        private string name; //이름 
        private string sno;    // 학번 
        // 정적 멤버 
        private static string InstructorName; // 담당강사 
        
        // C# 생성자 : 클래스이름, 리턴없다 
        public BitStudent()
        {
            name = "홍길동 ";
            sno = "100";
            InstructorName = "김"; 
        }

    


    }


    class Program
    {
        static void Main(string[] args)
        {
            BitStudent[] SList = new BitStudent[10]; 






           // 객체 생성 !! 
            BitClass bit = new BitClass(); // 객체 생성 !!  
            // bit :   인스턴스 --> 메모리상에 생성된클래스타입의 변수 ---> 객체 !! 
            bit.getName(); 


            




        }
    }
}

'C#' 카테고리의 다른 글

[C#] C#에서 제공하는 기본 타입들  (0) 2014.11.18
[C#] C# 언어의 특징  (0) 2014.11.18
[C#] Object 클래스란  (0) 2014.11.18
[C#] 메소드  (0) 2014.11.18
[C#] cs함수  (0) 2014.11.18
반응형
using System;
using System.Collections.Generic;
using System.Text;
//****************************************************************************
// System.Object 클래스 !! 
//****************************************************************************
//  -   모든 C#  객체들의 부모가 되는 클래스 !! 
// -  Object  클래스에 대한 상속은 암시적이다 !! 


namespace ObjectClass
{
    class Program    
    {
        void foo()
        { 
            // System.Object 클래스 의 멤버 !! 

/*         this.Equals : 객체간의 동등성을 비교 --> 같은 객체인가? 
           this.GetHashCode  :  객체만이 갖고 있는 고유의 해쉬값을 리턴 
           this.GetType        :  실행시간에 실행중인 객체의 타입정보 !! 
           this.MemberwiseClone  :  복사본 객체. 복제  
           this.ToString    :  객체를 문자열로 변환 !! 
 */
        }
            
        static void Main(string[] args)
        {
            string str1 = "hello";
            string str2 = "hello";

            str1 = str2; 

           // if (str1.Equals(str2))
            //    Console.WriteLine("같다");
            int a = 10; 
            Console.WriteLine(a.ToString());



        }
    }
}

'C#' 카테고리의 다른 글

[C#] C# 언어의 특징  (0) 2014.11.18
[C#] C# 객체 지향 프로그래밍!!  (0) 2014.11.18
[C#] 메소드  (0) 2014.11.18
[C#] cs함수  (0) 2014.11.18
[C#] WindowForm에서 데이터베이스를 사용한 프로그램  (0) 2014.11.18
반응형
using System;
using System.Collections.Generic;
using System.Text;
// 메소드  :  멤버 함수를 OOP적으로 부르는 용어 !!
// 함수 -- 메소드 --  펑션 -- 프로시져 

// 오버 로딩 제공  
//  -- > 같은 이름의 함수가 여러개 존재하는것  
// --> 메소드의 이름은 같지만 시그니쳐 ( 매개변수, 리턴) 가 다르면
//      여러개의 메소드를 구현할수 있다 !! 
//  -----> 같은 기능을 수행하지만.. 매개변수 정보가 다를경우 !! 
/*
class Person
{
    public Person(int age, string name)
    { 
    
    }
    public Person(int age, string name, int money)
    { 
    
    }
    // 단점, 코드의 가독성이 떨어질수 있다 !! 
    // 여러개의 함수가 존재 --> 관리가 어렵다 !! 
    public void foo(int a) { }
 //   public void foo(int * a) { }
    public void foo(out int a) { a = 10; }
    public void foo(ref int a ) { } // 접근 지정자는 오버로딩에 영향을 주지 않는다 !! 
    private voㅂid foo(ref int a) { }
    private int foo(ref int a) { return 0;  }   // 리턴은 타입은 오버로딩에 영향을 주지 않는다 !! 
    private void foo( params  a) { } //params 는 불간능 !! 

}
 */
// 메소드의 시그니쳐  --->다른 메서드들과 구분하기위한 방법 !! 
// 1) 메서드이름 :  고유한 이름 
// 2) 파라미터의 형식 : 파라이터의 타입에 따라 구분한다 .
// 3) 파라미터의 개수  
// 4) 파라미터의 변경자 :  ref , out !! 


// 오버 라이딩  제공 !! 
// -->   부모에서 정의한 함수를 자식에서 재정의 하는것 
class Anamal 
{   
    // C#에서 가상함수를 구현 !! 
    public  virtual void Die()
    {
        Console.WriteLine(" 으악 !! ");
    }
}

class Person : Anamal
{   
    // override 
    // new 
    // sealed 메소드 :  오버라이딩을 더이상 못하게 해라 !! 
    public override sealed void Die() { Console.WriteLine(" Person 으악 !! "); }
}

class Student : Person
{
    public override void Die() { } 
}

namespace Method
{
    class Program
    {
        static void Main(string[] args)
        {    
            // C++ virtual 키워드의 효과 !! 
            Person  p = new Person();
            p.Die();
        }
    }
}

반응형
using System;
using System.Collections.Generic;
using System.Text;

namespace CS함수
{
    class Program
    {
        // call by value , call by ref 
        // 1)  함수 내부로 인자를 전달하는 메카니즘 !! 
        //   -- > in Input Parameter : 

        // 1) 1개의 배열을 매개변수로 받아서 화면에 출력하는 함수 
        //  --> input  
        //2) 1개의 배열을 매개변수로 받아서 사용자에게 값을 입력하는 함수
        // --> output 
        // input : call by value 
        // out :  call by Ref 
        // call by value 
     /*   static void Add(out int No) //  out :   포인터의 전달 -> call by Ref !! 
        {
            // out : 값을 전달하기 위한 목적으로는 사용할수 없다 !! 
            No = 11;
            Console.WriteLine(No); //?? 
        }*/
        static void Add(ref int No)
        {
            No++;
            Console.WriteLine(No); //?? 
        }

        // out. ref 둘다 call by ref !! 
        // C#에서는 포인터가 없기때문에  포인터를 통해서 구현하던 call by ref 기능을 !! 
        //  out ,  ref키워드를 통해서 구현 한다 !! 
        // 단, 차이는 !! 
        // ref는 포인터와 완전히 동일한 형태로 call by ref를 구현하지만...
        // out :  반드시  값의 할당 필요하다 !! 


        // 가변 인자 함수 !! 
        // 함수로 전달되어지는 파라미터의 갯수가 가변적인 함수..
        // ex)  printf, scanf
        // printf함수는 파라미터가 몇개인가?? 
       //  printf("%d %d",10,10); 


       /* static long Sum( params long []  ParamList )
        {
            long Result = 0;
            foreach (long item in ParamList)
            {
                Result += item;
            }
            return Result; 
        }*/
        static string Sum(params Object[] ParamList)
        {
            string Result = "";
            foreach (Object item in ParamList)
            {
                Result += item.ToString();
            }
            return Result;
        }

        static void Main(string[] args)
        {


         //   Console.WriteLine("{0}    {1}    {2}", 10, "20", 30.0); 
           Console.WriteLine(Sum(10, 20, 30, 20,111,"60"));
          /*  int No = 10;
            Console.WriteLine(No);
            Add(ref No );
            Console.WriteLine(No);
        */
       }
    }
}

반응형
WindowForm 을 사용한 프로그램을 만들어보자!!!!

데이터베이스로는 insert, select, delete를 사용하여 프로그램을 개발해보자!!


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 DB_1;

namespace aaaa
{
    public partial class Form1 : Form
    {
        public void database()
        {
            dataGridView1.Rows.Clear();
            string[] data = new string[8];

            try
            {
                XDB myDB = new XDB(
                "Provider=Microsoft.ACE.OLEDB.12.0; " +
                "Data Source=../../../data.accdb; " +
                "Persist Security Info=False");

                string query = "select * from bb";
                myDB.Query(query);
                while (myDB.ReadNext())
                {
                    data[0] = myDB.GetData("No");
                    data[1] = myDB.GetData("등록과");
                    data[2] = myDB.GetData("접수일시");
                    data[3] = myDB.GetData("이름");
                    data[4] = myDB.GetData("주민번호");
                    data[5] = myDB.GetData("주소");
                    data[6] = myDB.GetData("HP");
                    data[7] = myDB.GetData("의사명");
                    dataGridView1.Rows.Add(data);
                }

            }
            catch (Exception)
            {
                MessageBox.Show("DB 연동이 안되었습니다.");
            }
        }

        public Form1()
        {
            InitializeComponent();
            database();

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox5.Text = listBox1.SelectedItem.ToString();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
             listBox1.Items.Clear();
            listBox1.Items.Add(this.comboBox1.SelectedItem.ToString());

            switch (this.comboBox1.SelectedItem.ToString())
            {
                case "내과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("내과 담당의사 이상준");
                    listBox1.Items.Add("내과 담당의사 이한수");
                    listBox1.Items.Add("내과 담당의사 채준영");
                    listBox1.Items.Add("내과 담당의사 이상신");
                    listBox1.Items.Add("내과 담당의사 이화영");
                    break;
                case "외과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("외과 담당의사 상주니");
                    listBox1.Items.Add("외과 담당의사 정한조");
                    listBox1.Items.Add("외과 담당의사 총장님");
                    listBox1.Items.Add("외과 담당의사 전현우");
                    listBox1.Items.Add("외과 담당의사 강병익");
                    break;
                case "산부인과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("산부인과 담당의사 주니주니");
                    listBox1.Items.Add("산부인과 담당의사 권규현");
                    listBox1.Items.Add("산부인과 담당의사 주수홍");
                    listBox1.Items.Add("산부인과 담당의사 최광호");
                    listBox1.Items.Add("산부인과 담당의사 차광호");
                    break;
                case "정형외과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("정형외과 담당의사 윤수영");
                    listBox1.Items.Add("정형외과 담당의사 고아라");
                    listBox1.Items.Add("정형외과 담당의사 이슬빈");
                    listBox1.Items.Add("정형외과 담당의사 이재욱");
                    listBox1.Items.Add("정형외과 담당의사 현성필");
                    break;
                case "방사선과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("방사선과 담당의사 김태우");
                    listBox1.Items.Add("방사선과 담당의사 김태수");
                    listBox1.Items.Add("방사선과 담당의사 전수영");
                    break;
                case "이비인후과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("이비인후과 담당의사 유수정");
                    listBox1.Items.Add("이비인후과 담당의사 길병열");
                    listBox1.Items.Add("이비인후과 담당의사 한조");
                    listBox1.Items.Add("이비인후과 담당의사 반야산");
                    listBox1.Items.Add("이비인후과 담당의사 이건양");
                    break;
                case "안과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("안과 담당의사 유수정");
                    listBox1.Items.Add("안과 담당의사 길병열");
                    listBox1.Items.Add("안과 담당의사 한조");
                    listBox1.Items.Add("안과 담당의사 반야산");
                    listBox1.Items.Add("안과 담당의사 이건양");
                    break;
                case "소아과":
                    listBox1.Items.Clear();
                    listBox1.Items.Add("소아과 담당의사 유수정");
                    listBox1.Items.Add("소아과 담당의사 길병열");
                    listBox1.Items.Add("소아과 담당의사 한조");
                    listBox1.Items.Add("소아과 담당의사 반야산");
                    listBox1.Items.Add("소아과 담당의사 이건양");
                    break;
                   
            }
        }

        private void 닫기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
        // 접수 버튼
        private void button1_Click(object sender, EventArgs e)
        {
            XDB myDB = new XDB(
           "Provider=Microsoft.ACE.OLEDB.12.0; " +
           "Data Source=../../../data.accdb; " +
           "Persist Security Info=False");

            myDB.Query("INSERT INTO bb(접수일시, 등록과, 이름, 주민번호,주소 ,HP,의사명) " +
                      "values(" +
                      "'" + textBox6.Text + "', " +
                      "'" + comboBox1.SelectedItem.ToString() + "', " +
                      "'" + textBox1.Text + "', " +
                      "'" + textBox2.Text + "', " +                
                       "'" + textBox3.Text + "', " +
                        "'" + textBox4.Text + "', " +
                      "'" + textBox5.Text + "' )"
                      );


            MessageBox.Show("접수가 완료 되었습니다");
            database();
        }
         //  닫기 버튼
        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }
        //삭제 버튼
        private void button3_Click(object sender, EventArgs e)
        {
            XDB myDB = new XDB(
            "Provider=Microsoft.ACE.OLEDB.12.0; " +
            "Data Source=../../../data.accdb; " +
            "Persist Security Info=False");

            myDB.Query("DELETE FROM bb WHERE 주민번호 = " + "'" + textBox2.Text + "'");

            MessageBox.Show("삭제가 완료 되었습니다");
            database();
        }
        //초기화
        private void button4_Click(object sender, EventArgs e)
        {
            
        }

        private void 만든이ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 rm2 = new Form2();
            rm2.ShowDialog();
        }
        
    }
}

DB_1 구성
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Windows.Forms;

namespace DB_1
{
    public class XDB
    {
        private OleDbConnection conn = null;
        private OleDbCommand comm = null;
        private OleDbDataReader read = null;

        public XDB(string connectionString)
        {
            conn = new OleDbConnection();
            comm = new OleDbCommand();
            try
            {
                conn.ConnectionString = connectionString;
                conn.Open();
                comm.Connection = conn;
            }
            catch (Exception e)
            {
                conn = null;
                comm = null;
                MessageBox.Show(e.ToString());
            }
        }//XDB()
        //----------------------------------------
        //insert, delete, update같은 데이터를 읽지는 않고
        //처리만 하는 함수
        public bool NonQuery(string query)
        {
            if (conn == null || comm == null)
            {
                MessageBox.Show("DB가 연결되어 있지 않습니다.");
                return false;
            }

            try
            {
                comm.CommandText = query;
                comm.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
            return true;
        }//NonQuery()
        //---------------------------------------
        public bool Query(string query)
        {
            if (conn == null || comm == null)
            {
                MessageBox.Show("DB가 연결되어 있지 않습니다.");
                return false;
            }

            if (read != null) read.Close();

            try
            {
                comm.CommandText = query;
                read = comm.ExecuteReader();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
                return false;
            }
            return true;
        }//Query()
        //----------------------------------------------
        public bool ReadNext()
        {
            if (read != null) return read.Read();
            return false;
        }
        //--------------------------------------------
        public string GetData(string name)
        {
            if (read != null) return read[name].ToString();
            MessageBox.Show("읽은 데이터가 없습니다.");
            return "";
        }
    }//class
}//nameSpace


반응형
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Windows.Forms;

namespace DB_2
{
    public class XDB
    {
        private OleDbConnection conn = null;
        private OleDbCommand comm = null;
        private OleDbDataReader read = null;

        public XDB(string connectionString)
        {
            conn = new OleDbConnection();
            comm = new OleDbCommand();
            try
            {
                conn.ConnectionString = connectionString;
                conn.Open();
                comm.Connection = conn;
            }
            catch (Exception e)
            {
                conn = null;
                comm = null;
                MessageBox.Show(e.ToString());
            }
        }//XDB()
        //----------------------------------------
        //insert, delete, update같은 데이터를 읽지는 않고
        //처리만 하는 함수
        public bool NonQuery(string query)
        {
            if (conn == null || comm == null)
            {
                MessageBox.Show("DB가 연결되어 있지 않습니다.");
                return false;
            }

            try
            {
                comm.CommandText = query;
                comm.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
            return true;
        }//NonQuery()
        //---------------------------------------
        public bool Query(string query)
        {
            if (conn == null || comm == null)
            {
                MessageBox.Show("DB가 연결되어 있지 않습니다.");
                return false;
            }

            if (read != null) read.Close();

            try
            {
                comm.CommandText = query;
                read = comm.ExecuteReader();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
                return false;
            }
            return true;
        }//Query()
        //----------------------------------------------
        public bool ReadNext()
        {
            if (read != null) return read.Read();
            return false;
        }
        //--------------------------------------------
        public string GetData(string name)
        {
            if (read != null) return read[name].ToString();
            MessageBox.Show("읽은 데이터가 없습니다.");
            return "";
        }
    }//class
}//nameSpace


반응형

현재 텍스트파일의 내용들을 데이터베이스인 엑세스파일에 데이터를 넣어주는 소스입니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace DB_1
{
    class Program
    {

        static void Main(string[] args)
        {
            OleDbConnection myConnection = null;
            OleDbCommand myCommand = null;

            myConnection = new OleDbConnection();
            myCommand = new OleDbCommand();

            try
            {
                //db 연결하는 부분
                myConnection.ConnectionString =
                    "Provider=Microsoft.ACE.OLEDB.12.0; " +
                    "Data Source=../../../DBfile/WORKER_DB.accdb; " +
                    "Persist Security Info=False";

                myConnection.Open();

                //컴멘드 객체에 연결된 연결 객체를 대입
                myCommand.Connection = myConnection;

                // /////////////////////////////////////////////
                //우편번호가 있는 텍스트 파일 열기
                System.IO.StreamReader DBfile =
                    new System.IO.StreamReader("../../../DBfile/TEST_UTF8.txt");

                string zipStr;
                long count = 0;

                //현재의 테이블 내용을 삭제. 왜냐하면 테이블에 주키가 없기 
                //때문에 삭제하지 않으면 이 프로그램을 실행 할 때마다
                //같은 데이터가 추가되기 때문이다.
                myCommand.CommandText = "delete from WORKER";
                myCommand.ExecuteNonQuery();

                //비어 있는 DB 테이블에 텍스트 파일의 모든 내용을 
                //테이블에 추가
                while (!DBfile.EndOfStream)
                {
                    //텍스트 파일에서 한 줄의 내용을 읽기
                    zipStr = DBfile.ReadLine();

                    //tab키를 구분자로 사용하여 문자열을 여러개의 
                    //작은 문자열로 분리
                    string[] words = zipStr.Split('\t');

                    string query =
                        "insert into WORKER (NM, NUM, BU, LEV, BUM, TEL, INTEL, JUSO) ";

                    query += "values (";
                    query += "'" + words[0] + "', ";
                    query += "'" + words[1] + "', ";
                    query += "'" + words[2] + "', ";
                    query += "'" + words[3] + "', ";
                    query += "'" + words[4] + "', ";
                    query += "'" + words[5] + "', ";
                    query += "'" + words[6] + "', ";
                    query += "'" + words[7] + "'";
                    query += ")";

                    //Console.WriteLine(query);

                    //명령객체의 CommandText에 쿼리 문자열을 대입
                    myCommand.CommandText = query;

                    //쿼리를 실행
                    myCommand.ExecuteNonQuery();

                    count++;

                    if ((count % 1) == 0) Console.WriteLine(count);
                }//while

                //텍스트 파일 닫기
                DBfile.Close();

                //DB 연결 끊기
                myConnection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }//Main
    }
}

반응형


info.zip

엑세스 2007로 데이터베이스를 사용하여 연동되는 프로그램입니다.

+ Recent posts