Visual C# 2005 또는 Visual C# 사용 방법NET는 DataSet 객체를 통해 데이터베이스를 업데이트합니다.

13515 단어 .net
본고는 데이터베이스에서 데이터를 불러오는 방법을 단계별로 보여 줍니다.
DataSet, 이 데이터를 수정하는 방법, 그리고 데이터베이스로 다시 보내서 원본 데이터 원본을 업데이트하는 방법.
DataSet 객체는 Microsoft입니다.NET Framework에서 데이터 액세스의 주요 부분은 테이블, 뷰 및 관계를 저장할 수 있는 메모리의 객체입니다.
정상으로 돌아가다

요구 사항


//
loadTOCNode(2, 'summary');
//다음 표에는 권장되는 하드웨어, 소프트웨어, 네트워크 인프라 및 필요한 서비스 팩이 정리되어 있습니다.
  • Microsoft Windows Server 2003, Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server 또는 Microsoft Windows NT 4.0 Server
  • Microsoft SQL Server 버전 7.0, Microsoft SQL Server 2000 또는 PUBS 샘플 데이터베이스가 설치된 Microsoft 데이터 엔진(MSDE)
  • Microsoft Visual Studio 2005 또는 Microsoft Visual StudioNET

  • 이 문서에서는 다음 항목에 대해 잘 알고 있다고 가정합니다.
  • 데이터베이스 용어
  • 구조적 쿼리 언어(SQL)
  • 정상으로 돌아가다

    DataSet 객체를 통해 데이터베이스를 업데이트하는 방법


    //
    loadTOCNode(2, 'summary');
    //이 절에서는 어떻게 사용하는지 보여 준다
    DataSet 객체는 데이터베이스의 데이터를 업데이트합니다.사용 가능
    SqlCommand 객체는 데이터베이스에 데이터를 직접 삽입, 업데이트 및 삭제하는 것이 중요합니다.
    이 문서를 더 잘 이해하려면 아래 기사 번호를 클릭하여 Microsoft Knowledgebase의 해당 기사를 확인하십시오.
    314145
    (http://support.microsoft.com/kb/314145/) Visual C# 사용 방법NET가 데이터베이스에서 DataSet 객체 채우기
    기사
    314145
    (http://support.microsoft.com/kb/314145/)에서 다루는 몇 가지 주제는 데이터베이스에서 데이터를 검색하여 전송하는 방법
    DataSet에서
    DataSet이 데이터베이스와 차별화되는 방법 및 방법
    로드
    DataSet 을 사용하면 데이터를 수정할 수 있습니다.
    DataSet은 이러한 변경 사항을 추적합니다.... 할 만하다
    DataSet 객체는 데이터베이스에서 검색되어 메모리에 캐시된 데이터로 간주됩니다.
    DataSet 객체는 테이블, 관계식 및 구속조건을 포함하는 컬렉션으로 구성됩니다.
    업데이트하기
    DataSet 업데이트 내용을 데이터베이스로 다시 보내려면 다음 절차를 따르십시오.
  • Visual Studio 2005 또는 Visual Studio를 시작합니다.NET.
  • Visual C#에 새 콘솔 애플리케이션을 만듭니다.기본적으로 Visual Studio는 정적 클래스와 빈 Main() 프로세스를 만듭니다.
  • 프로젝트에 System 및 System이 포함되어 있는지 확인합니다.Data 네임스페이스의 참조System, System에서Data 및 System.Data.SqlClient 네임스페이스에서 using 문을 사용하면 다음 코드에서 선언을 제한할 필요가 없습니다.다른 모든 성명 전에 이 문장을 사용해야 한다.
    
    using System;
    using System.Data;
    using System.Data.SqlClient;
                                            
    

  • 데이터를 수정하고 변경 사항을 데이터베이스로 보내기 전에 이 정보를 DataSet에 로드해야 합니다.자세한 내용은 314145(http://support.microsoft.com/kb/314145/) .중복을 피하기 위해 이 단계의 코드는 상세하게 제공되지 않습니다.다음 코드의 연결 문자열은 로컬 컴퓨터(또는 코드를 실행 중인 컴퓨터)에 있는 SQL Server를 가리킵니다.요약하자면 먼저 연결을 만들고 데이터 어댑터를 만들어서 데이터를 데이터셋에 채웁니다.참고: 이 코드를 실행하기 전에 User ID 과Password 를 올바른 값으로 변경해야 합니다.이 사용자 ID에 데이터베이스에서 이 작업을 수행하는 데 필요한 적절한 권한이 있는지 확인하십시오.
    
    string sConnectionString;
    
    // Modify the following string to correctly connect to your SQL Server.
    sConnectionString = "Password=<strong password>;User ID=<username>;"
            + "Initial Catalog=pubs;"
            + "Data Source=(local)";
    
    SqlConnection objConn
            = new SqlConnection(sConnectionString);
    objConn.Open();
    
    // Create an instance of a DataAdapter.
    SqlDataAdapter daAuthors 
            = new SqlDataAdapter("Select * From Authors", objConn);
    
    // Create an instance of a DataSet, and retrieve data from the Authors table.
    DataSet dsPubs = new DataSet("Pubs");
    daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors");
    daAuthors.Fill(dsPubs,"Authors");
                                            
    

  • 데이터가 로드되었으므로 수정할 수 있습니다.행(또는 레코드)을 추가하는 방법에는 여러 가지가 있습니다.코드 예제에서는 3단계 프로세스를 사용합니다.
  • DataTable에서 새로운 DataRow 객체를 가져옵니다.
  • 필요에 따라 DataRow 필드 값을 설정합니다.
  • 새로운 객체를 DataTable에 전달합니다.Rows 컬렉션의 Add 방법입니다.

  • 다음 코드를 단계 4의 코드 뒤에 붙여넣습니다.
    
    //****************
    // BEGIN ADD CODE 
    // Create a new instance of a DataTable.
    DataTable tblAuthors;
    tblAuthors = dsPubs.Tables["Authors"];
    
    DataRow drCurrent;
    // Obtain a new DataRow object from the DataTable.
    drCurrent = tblAuthors.NewRow();
    
    // Set the DataRow field values as necessary.
    drCurrent["au_id"] = "993-21-3427";
    drCurrent["au_fname"] = "George";
    drCurrent["au_lname"] = "Johnson";
    drCurrent["phone"] = "800 226-0752";
    drCurrent["address"] = "1956 Arlington Pl.";
    drCurrent["city"] = "Winnipeg";
    drCurrent["state"] = "MB";
    drCurrent["contract"] = 1;
    
    // Pass that new object into the Add method of the DataTable.
    tblAuthors.Rows.Add(drCurrent);
    Console.WriteLine("Add was successful, Click any key to continue!!");
    Console.ReadLine();
    
    // END ADD CODE  
                                            
    

  • 기존 행을 편집하려면 해당 DataRow 객체를 가져와 열 또는 열에 새 값을 입력합니다.테이블의 구조와 데이터를 불러왔기 때문에 (4단계에서 FillSchema를 호출했기 때문에) 정확한 줄을 찾아야 합니다. 이 과정은 매우 간단합니다.구조가 있으면, 테이블은 어느 열이 메인 키인지 알 수 있을 뿐만 아니라, Rows가 집합한Find 방법도 사용할 수 있다.Find 메서드는 DataRow 객체를 반환하고 기본 키에 특정 값이 있습니다(이 경우 au id).DataRow가 있으면 열을 수정할 수 있습니다.BeginEdit와 EndEdit의 수정 사항을 포장할 필요는 없지만, 포장은 DataSet이 반드시 완성해야 하는 작업을 간소화하고, DataSet이 EndEdit를 호출하는 동시에 검증 검사를 수행할 수 있도록 합니다.다음 코드를 ADD 코드 다음에 붙여넣습니다.
    
    //*****************
    // BEGIN EDIT CODE 
    
    drCurrent = tblAuthors.Rows.Find("213-46-8915");
    drCurrent.BeginEdit();
    drCurrent["phone"] = "342" + drCurrent["phone"].ToString().Substring(3);
    drCurrent.EndEdit();
    Console.WriteLine("Record edited successfully, Click any key to continue!!");
    Console.ReadLine();
    
    // END EDIT CODE  
                                            
    

  • 이 모든 변경 사항을 사용하여 원본 데이터베이스를 업데이트하려면 DataSet을 DataAdapter 객체의 Update 방법으로 전달합니다.단, Update를 호출하기 전에 DataAdapter 대상의 InsertCommand, UpdateCommand, DeleteCommand 속성을 설정해야 합니다.SQL을 수동으로 작성하고 해당 SqlCommand 객체로 이 세 가지 속성을 채울 수 있지만 Visual Studio를 사용할 수도 있습니다.NET는 세 명령을 자동으로 생성합니다.필요할 때 필요한 명령을 생성하려면 SqlCommandBuilder 객체의 인스턴스를 만들고 이 구조 함수의 DataAdapter를 사용해야 합니다.이 방법을 사용하려면, 테이블에 키 정보가 있어야 합니다.주 키 정보에 액세스하려면 FillSchema를 호출한 다음 DataAdapter의 MissingSchemaAction 속성을 AddWithKey로 설정하거나 코드에서 주 키를 수동으로 설정합니다.다음 코드를 EDIT 코드 뒤에 붙여넣습니다.
    
    //*****************
    // BEGIN SEND CHANGES TO SQL SERVER 
    
    SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors);
    daAuthors.Update(dsPubs, "Authors");
    Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
    Console.ReadLine();
    
    // END SEND CHANGES TO SQL SERVER
                                            
    

  • 행을 완전히 삭제하려면 DataRow 객체의 Delete 메서드를 사용합니다.Rows 컬렉션에는 행이 삭제된 것처럼 보이는 Remove와 RemoveAt 두 가지 방법이 포함되어 있지만 실제로는 컬렉션에서만 행이 제거됩니다.삭제 결과는 Delete 메서드만 소스 데이터베이스로 전송됩니다.다음 코드를 SEND CHANGES TO SQL SERVER 코드 뒤에 붙여넣습니다.
    
    //*****************
    //BEGIN DELETE CODE 
    
    drCurrent = tblAuthors.Rows.Find("993-21-3427");
    drCurrent.Delete();
    Console.WriteLine("Record deleted successfully, Click any key to continue!!"); 
    Console.ReadLine();
    
    //END DELETE CODE 
                                            
    

  • 이전에 추가한 레코드를 제거하기 위해 SQL Server에 변경 사항을 보냅니다.다음 코드를 DELETE 코드에 붙여넣습니다.
    
    //*****************
    // CLEAN UP SQL SERVER
    daAuthors.Update(dsPubs, "Authors");
    Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
    Console.ReadLine();
                                            
    

  • 프로젝트를 저장합니다.
  • [디버깅] 메뉴에서 [시작]을 클릭하여 프로젝트를 실행합니다.코드의 실행 진도를 표시하고 코드의 실행 과정에서 데이터의 현재 상태를 볼 수 있도록 몇 개의 메시지 상자가 나타날 것입니다.

  • 정상으로 돌아가다

    전체 코드 목록


    //
    loadTOCNode(2, 'summary');
    //
    
    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace PopulateDataSet
    {
    
        /// <summary>
        /// Summary description for Class1.
        /// </summary>
        class Class1
        {
            static void Main(string[] args)
            {
                string sConnectionString;
    
                // Modify the following string to correctly connect to your SQL Server.
                sConnectionString = "Password=;User ID=sa;"
                    + "Initial Catalog=pubs;"
                    + "Data Source=(local)";
    
                SqlConnection objConn
                    = new SqlConnection(sConnectionString);
                objConn.Open();
    
                // Create an instance of a DataAdapter.
                SqlDataAdapter daAuthors 
                    = new SqlDataAdapter("Select * From Authors", objConn);
    
                // Create an instance of a DataSet, and retrieve 
                // data from the Authors table.
                DataSet dsPubs = new DataSet("Pubs");
                daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors");
                daAuthors.Fill(dsPubs,"Authors"); 
                //****************
                // BEGIN ADD CODE 
                // Create a new instance of a DataTable.
                DataTable tblAuthors;
                tblAuthors = dsPubs.Tables["Authors"];
    
                DataRow drCurrent;
                // Obtain a new DataRow object from the DataTable.
                drCurrent = tblAuthors.NewRow();
    
                // Set the DataRow field values as necessary.
                drCurrent["au_id"] = "993-21-3427";
                drCurrent["au_fname"] = "George";
                drCurrent["au_lname"] = "Johnson";
                drCurrent["phone"] = "800 226-0752";
                drCurrent["address"] = "1956 Arlington Pl.";
                drCurrent["city"] = "Winnipeg";
                drCurrent["state"] = "MB";
                drCurrent["contract"] = 1;
    
                // Pass that new object into the Add method of the DataTable.
                tblAuthors.Rows.Add(drCurrent);
                Console.WriteLine("Add was successful, Click any key to continue!!");
                Console.ReadLine();
    
                // END ADD CODE   
                //*****************
                // BEGIN EDIT CODE 
    
                drCurrent = tblAuthors.Rows.Find("213-46-8915");
                drCurrent.BeginEdit();
                drCurrent["phone"] = "342" + drCurrent["phone"].ToString().Substring(3);
                drCurrent.EndEdit();
                Console.WriteLine("Record edited successfully, Click any key to continue!!");
                Console.ReadLine();
                            
                // END EDIT CODE   
                //*****************
                // BEGIN SEND CHANGES TO SQL SERVER 
    
                SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors);
                daAuthors.Update(dsPubs, "Authors");
                Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
                Console.ReadLine();
                            
                // END SEND CHANGES TO SQL SERVER 
                //*****************
                //BEGIN DELETE CODE 
    
                drCurrent = tblAuthors.Rows.Find("993-21-3427");
                drCurrent.Delete();
                Console.WriteLine("SRecord deleted successfully, Click any key to continue!!"); 
                Console.ReadLine();
           
                //END DELETE CODE  
                //*****************
                // CLEAN UP SQL SERVER
                daAuthors.Update(dsPubs, "Authors");
                Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
                Console.ReadLine();                 
                            
            }
        }
    }
                                    
    

    정상으로 돌아가다

    참고 자료


    ADO를 사용하는 방법NET, DataSet 대상과 SQL에 대한 더 많은 정보는 아래의 Microsoft 사이트를 방문하십시오: 데이터 접근 (MSDN의 소리 칼럼) http:...


    //
    loadTOCNode(1, 'references');
    //
    ADO를 사용하는 방법NET、
    DataSet 객체 및 SQL에 대한 자세한 내용은 다음 Microsoft 웹 사이트를 참조하십시오.
    데이터 액세스 심층 분석(
    MSDN 사운드 칼럼)
    http://msdn.microsoft.com/columns/
    (http://msdn.microsoft.com/columns/)
    ADO 프로그래머를 위한 ADOONET
    http://msdn.microsoft.com/library/default.asp?url=/library/zh-cn/dndotnet/html/adonetprogmsdn.asp
    (http://msdn.microsoft.com/library/default.asp?url=/library/zh-cn/dndotnet/html/adonetprogmsdn.asp)
    MSDN Online .NET 개발자 센터
    http://msdn2.microsoft.com/zh-cn/netframework/default.aspx

    좋은 웹페이지 즐겨찾기