메모
클래스 및 관련 클래스는 DataSet 2000년대 초반의 레거시 .NET Framework 기술로, 애플리케이션이 데이터베이스와 연결이 끊긴 동안 애플리케이션이 메모리의 데이터로 작업할 수 있도록 합니다. 이 기술은 사용자가 데이터를 수정하고 변경 내용을 데이터베이스에 다시 유지할 수 있도록 하는 앱에 특히 유용합니다. 데이터 세트는 입증된 성공적인 기술이지만 새 .NET 애플리케이션에 권장되는 방법은 Entity Framework Core를 사용하는 것입니다. Entity Framework는 테이블 형식 데이터를 개체 모델로 사용하는 보다 자연스러운 방법을 제공하며 더 간단한 프로그래밍 인터페이스를 제공합니다.
데이터베이스에서 데이터를 조작하는 애플리케이션을 만들 때 일반적으로 연결 문자열 정의, 데이터 삽입 및 저장 프로시저 실행과 같은 작업을 수행합니다. 이 문서를 따르시면 Visual C# 또는 Visual Basic 및 ADO.NET을 사용하여 forms over data (FOD) Windows Forms 애플리케이션 내에서 데이터베이스와 상호 작용하는 방법을 알 수 있습니다. 데이터 세트, SQL에 대한 LINQ(Language-Integrated Query) 및 Entity Framework를 비롯한 모든 .NET 데이터 기술은 궁극적으로 이 문서에 나와 있는 단계와 유사한 단계를 수행합니다.
이 문서에서는 데이터베이스에서 데이터를 빠르게 가져오는 방법을 보여 줍니다. 애플리케이션이 사소한 방법으로 데이터를 수정하고 데이터베이스를 업데이트해야 하는 경우 Entity Framework 및 데이터 바인딩을 사용하는 것이 좋습니다. 이렇게 하면 사용자 인터페이스 컨트롤이 기본 데이터의 변경 내용과 자동으로 동기화됩니다.
이 자습서의 전체 코드에 액세스하려면 C# 및 Visual Basic용 Visual Studio 문서 GitHub 리포지토리를 참조하세요.
중요하다
코드를 단순하게 유지하기 위해 프로덕션 준비 예외 처리는 포함하지 않습니다.
필수 구성 요소
.NET 데스크톱 개발 및 데이터 저장 및 처리 워크로드가 설치된 Visual Studio. 설치하려면 Visual Studio 설치 관리자를 열고 수정하려는 Visual Studio 버전 옆에 있는 수정 을 선택합니다.
SQL Server Express LocalDB. SQL Server Express LocalDB가 없는 경우 SQL Server 다운로드 페이지설치할 수 있습니다.
이 문서에서는 사용자가 Visual Studio IDE의 기본 기능에 익숙하다고 가정합니다. 또한 Windows Forms 애플리케이션을 만들고, 프로젝트에 양식을 추가하고, 폼에 단추 및 기타 컨트롤을 추가하고, 컨트롤 속성을 설정하고, 간단한 이벤트를 코딩할 수 있다고 가정합니다. 이러한 작업에 익숙하지 않은 경우 이 연습을 시작하기 전에 C#을 사용하여 Visual Studio에서 Windows Forms 앱 만들기 자습서 또는 Visual Basic을 사용하여 Visual Studio에서 Windows Forms 앱 만들기 자습서를 완료하세요.
샘플 데이터베이스 설정
다음 단계에 따라 샘플 데이터베이스를 만듭니다.
Visual Studio에서 서버 탐색기 창을 엽니다.
데이터 연결을 마우스 오른쪽 단추로 클릭하고 새 SQL Server 데이터베이스 만들기를 선택합니다.
서버 이름에 (localdb)\mssqllocaldb를 입력합니다.
새 데이터베이스 이름에 대해 Sales를 입력한 다음 확인을 선택합니다.
Visual Studio는 서버 탐색기의 데이터 연결 노드 아래에 빈 Sales 데이터베이스를 만듭니다.
Sales 데이터 연결을 마우스 오른쪽 단추로 클릭하고 새 쿼리를 선택합니다.
쿼리 편집기 창이 열립니다.
Sales Transact-SQL 스크립트 클립보드에 복사하세요.
T-SQL 스크립트를 쿼리 편집기 창에 붙여넣은 다음 실행을 선택합니다.
잠시 후 쿼리 실행이 완료되고 데이터베이스 개체가 만들어집니다. 데이터베이스에는 고객 및 주문이라는 두 개의 테이블이 포함되어 있습니다. 이러한 테이블에는 처음에는 데이터가 포함되지 않지만 만든 애플리케이션을 실행할 때 데이터를 추가할 수 있습니다. 데이터베이스에는 5개의 기본 저장 프로시저도 포함되어 있습니다.
폼 만들기 및 컨트롤 추가
Windows Forms 앱(.NET Framework) 템플릿을 사용하여 C# 또는 Visual Basic 프로젝트를 만들고 이름을 SimpleDataApp으로 지정합니다.
Visual Studio는 Form1이라는 빈 Windows 양식을 포함하여 프로젝트와 여러 파일을 만듭니다.
솔루션 탐색기에서 프로젝트에 두 개의 Windows 양식을 추가하여 총 3개의 폼을 가지도록 하고 다음 이름을 지정합니다.
탐색
신규고객
채우기또는취소
각 양식에 대해 다음 그림에 표시된 텍스트 상자, 단추 및 기타 컨트롤을 추가합니다. 각 컨트롤에 대해 테이블에서 설명하는 속성을 설정합니다.
메모
그룹 상자와 레이블 컨트롤은 명확성을 더하지만 코드에는 사용되지 않습니다.
탐색 양식
탐색 폼에 대한 컨트롤
컨트롤 텍스트 컨트롤 형식 컨트롤 속성 계정 추가 단추 이름 = btnGoToAdd 주문 입력 또는 취소 단추 Name = btnGoToFillOrCancel 출구 단추 Name = btnExit newCustomer 양식
NewCustomer 양식에 대한 컨트롤
레이블/컨트롤 텍스트 컨트롤 형식 컨트롤 속성 고객 이름 텍스트 상자 이름 = txtCustomerName 고객 ID 텍스트 상자 Name = txtCustomerID
읽기 전용 = 참거래처 만들기 단추 Name = btnCreateAccount 주문 금액 숫자 상하 조절 Name = numOrderAmount
소수자릿수 = 0
최대 = 5000주문 날짜 DateTimePicker Name = dtpOrderDate
형식 = 단축순서 지정 단추 Name = btnPlaceOrder 끝내다 단추 Name = btnAddFinish 다른 계정 추가 단추 Name = btnAddAnotherAccount FillOrCancel 양식
FillOrCancel 양식에 대한 컨트롤
레이블/컨트롤 텍스트 컨트롤 형식 컨트롤 속성 주문 ID 텍스트 상자 Name = txtOrderID 주문 찾기 단추 Name = btnFindByOrderID 주문을 채우는 경우... DateTimePicker Name = dtpFillDate
형식 = 단축(없음) 데이터 그리드 보기 (DataGridView) Name = dgvCustomerOrders
읽기 전용 = 참
RowHeadersVisible = False주문 취소 단추 Name = btnCancelOrder 주문 실행 단추 Name = btnFillOrder 끝내다 단추 Name = btnFinishUpdates
연결 문자열 저장
애플리케이션이 데이터베이스에 대한 연결을 열려고 하면 애플리케이션이 연결 문자열에 액세스할 수 있어야 합니다. 각 양식에서 문자열을 수동으로 입력할 필요가 없도록 하려면 프로젝트의 App.config 파일에 문자열을 저장합니다. 그런 다음 애플리케이션의 폼에서 메서드를 호출할 때 문자열을 반환하는 메서드를 만듭니다.
연결 문자열을 찾으려면 다음을 수행합니다.
서버 탐색기에서 Sales 데이터 연결을 마우스 오른쪽 단추로 클릭한 다음 속성을 선택합니다.
연결 문자열 속성을 찾아 해당 문자열 값을 클립보드에 복사합니다.
프로젝트에 연결 문자열을 저장하려면 다음을 수행합니다.
솔루션 탐색기에서 프로젝트 유형에 따라 다음 단계 중 하나를 수행합니다.
C# 프로젝트의 경우 프로젝트 아래에 있는 속성 노드를 확장한 다음 Settings.settings 파일을 엽니다.
Visual Basic 프로젝트의 경우 모든 파일 표시를 선택하고 내 프로젝트 노드를 확장한 다음 Settings.settings 파일을 엽니다.
이름 열에 connString을 입력합니다.
형식 목록에서 (연결 문자열)을 선택합니다.
범위 목록에서 애플리케이션선택합니다.
값 열에서 외부 따옴표 없이 연결 문자열을 입력한 다음 변경 내용을 저장합니다.
주의
실제 애플리케이션에서는 연결 문자열 및 구성 파일에 설명된 대로 연결 문자열을 안전하게 저장해야 합니다. 최상의 보안을 위해 연결 문자열에 암호를 저장하지 않는 인증 방법을 사용합니다. 예를 들어 온-프레미스 SQL Server 데이터베이스에 대한 Windows 인증입니다. 자세한 내용은 연결 문자열 저장 및 편집을 참조하세요.
양식에 대한 코드 작성
이 섹션에서는 각 양식이 수행하는 작업을 간략하게 서술합니다. 또한 양식에서 단추를 선택할 때 기본 논리를 정의하는 코드를 제공합니다.
탐색 양식
애플리케이션을 실행할 때 탐색 양식이 열리고 다음 단추가 포함됩니다.
계정 추가: NewCustomer 양식을 엽니다.
주문 입력 또는 취소: FillOrCancel 양식을 엽니다.
종료: 애플리케이션을 닫습니다.
탐색 폼을 시작 양식으로 만들기
C# 프로젝트의 경우:
솔루션 탐색기에서 Program.cs 엽니다.
줄을
Application.Run
다음으로 변경합니다.Application.Run(new Navigation());
Visual Basic 프로젝트의 경우:
솔루션 탐색기에서 프로젝트를 마우스 오른쪽 단추로 클릭하고 속성을 선택합니다.
프로젝트 디자이너에서 애플리케이션 탭을 선택한 다음 시작 개체 목록에서 탐색을 선택합니다.
탐색 양식에 대한 자동 생성된 이벤트 처리기 만들기
빈 이벤트 처리기 메서드를 만들려면 탐색 양식에서 세 개의 단추를 각각 두 번 클릭합니다. 단추를 두 번 클릭하면 디자이너 코드 파일에 자동 생성된 코드가 추가되어 단추 선택에서 이벤트를 발생시키는 데 사용할 수 있습니다.
디자이너에서 두 번 클릭 작업을 사용하는 대신 코드를 직접 복사하여 코드 파일에 붙여넣기로 결정한 경우 이벤트 처리기를 올바른 메서드로 설정해야 합니다.
폼에 대한 코드 파일의 속성 창에서 번개 모양 도구 모음 단추를 사용하여 이벤트 탭으로 전환합니다.
Click 속성을 검색하고 해당 값이 올바른 이벤트 처리기 메서드인지 확인합니다.
탐색 양식 논리에 대한 코드 추가
탐색 양식의 코드 페이지에서 다음 코드와 같이 단추 선택 이벤트 처리기 3개에 대한 메서드 본문을 완료합니다.
/// <summary>
/// Opens the NewCustomer form as a dialog box,
/// which returns focus to the calling form when it is closed.
/// </summary>
private void btnGoToAdd_Click(object sender, EventArgs e)
{
Form frm = new NewCustomer();
frm.Show();
}
/// <summary>
/// Opens the FillorCancel form as a dialog box.
/// </summary>
private void btnGoToFillOrCancel_Click(object sender, EventArgs e)
{
Form frm = new FillOrCancel();
frm.ShowDialog();
}
/// <summary>
/// Closes the application (not just the Navigation form).
/// </summary>
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
NewCustomer 양식
고객 이름을 입력한 다음 계정 만들기 단추를 선택하면 NewCustomer 양식에서 고객 계정을 만들고 SQL Server는 ID 값을 새 고객 ID로 반환합니다. 그런 다음, 금액 및 주문 날짜를 지정하고 주문 배치 단추를 선택하여 새 계정에 대한 주문을 할 수 있습니다.
NewCustomer 양식에 대한 자동 생성된 이벤트 처리기 만들기
네 개의 단추를 각각 두 번 클릭하여 NewCustomer 양식의 각 단추에 대해 빈 Click 이벤트 처리기를 만듭니다. 단추를 두 번 클릭하면 디자이너 코드 파일에 자동으로 생성된 코드가 추가되어 단추 선택 시 이벤트가 발생합니다.
NewCustomer 양식 논리에 대한 코드 추가
NewCustomer 양식 논리를 완료하려면 다음 단계를 수행합니다.
네임스페이스
System.Data.SqlClient
를 범위로 포함시켜 멤버의 이름을 완전히 정규화하지 않아도 되도록 합니다.
클래스에 일부 변수 및 도우미 메서드를 추가합니다.
// Storage for IDENTITY values returned from database. private int parsedCustomerID; private int orderID; /// <summary> /// Verifies that the customer name text box is not empty. /// </summary> private bool IsCustomerNameValid() { if (txtCustomerName.Text == "") { MessageBox.Show("Please enter a name."); return false; } else { return true; } } /// <summary> /// Verifies that a customer ID and order amount have been provided. /// </summary> private bool IsOrderDataValid() { // Verify that CustomerID is present. if (txtCustomerID.Text == "") { MessageBox.Show("Please create customer account before placing order."); return false; } // Verify that Amount isn't 0. else if ((numOrderAmount.Value < 1)) { MessageBox.Show("Please specify an order amount."); return false; } else { // Order can be submitted. return true; } } /// <summary> /// Clears the form data. /// </summary> private void ClearForm() { txtCustomerName.Clear(); txtCustomerID.Clear(); dtpOrderDate.Value = DateTime.Now; numOrderAmount.Value = 0; this.parsedCustomerID = 0; }
단추 선택 이벤트 처리기 4개에 대한 메서드 본문을 완료합니다.
/// <summary> /// Creates a new customer by calling the Sales.uspNewCustomer stored procedure. /// </summary> private void btnCreateAccount_Click(object sender, EventArgs e) { if (IsCustomerNameValid()) { // Create the connection. using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString)) { // Create a SqlCommand, and identify it as a stored procedure. using (SqlCommand sqlCommand = new SqlCommand("Sales.uspNewCustomer", connection)) { sqlCommand.CommandType = CommandType.StoredProcedure; // Add input parameter for the stored procedure and specify what to use as its value. sqlCommand.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 40)); sqlCommand.Parameters["@CustomerName"].Value = txtCustomerName.Text; // Add the output parameter. sqlCommand.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int)); sqlCommand.Parameters["@CustomerID"].Direction = ParameterDirection.Output; try { connection.Open(); // Run the stored procedure. sqlCommand.ExecuteNonQuery(); // Customer ID is an IDENTITY value from the database. this.parsedCustomerID = (int)sqlCommand.Parameters["@CustomerID"].Value; // Put the Customer ID value into the read-only text box. this.txtCustomerID.Text = Convert.ToString(parsedCustomerID); } catch { MessageBox.Show("Customer ID was not returned. Account could not be created."); } finally { connection.Close(); } } } } } /// <summary> /// Calls the Sales.uspPlaceNewOrder stored procedure to place an order. /// </summary> private void btnPlaceOrder_Click(object sender, EventArgs e) { // Ensure the required input is present. if (IsOrderDataValid()) { // Create the connection. using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString)) { // Create SqlCommand and identify it as a stored procedure. using (SqlCommand sqlCommand = new SqlCommand("Sales.uspPlaceNewOrder", connection)) { sqlCommand.CommandType = CommandType.StoredProcedure; // Add the @CustomerID input parameter, which was obtained from uspNewCustomer. sqlCommand.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int)); sqlCommand.Parameters["@CustomerID"].Value = this.parsedCustomerID; // Add the @OrderDate input parameter. sqlCommand.Parameters.Add(new SqlParameter("@OrderDate", SqlDbType.DateTime, 8)); sqlCommand.Parameters["@OrderDate"].Value = dtpOrderDate.Value; // Add the @Amount order amount input parameter. sqlCommand.Parameters.Add(new SqlParameter("@Amount", SqlDbType.Int)); sqlCommand.Parameters["@Amount"].Value = numOrderAmount.Value; // Add the @Status order status input parameter. // For a new order, the status is always O (open). sqlCommand.Parameters.Add(new SqlParameter("@Status", SqlDbType.Char, 1)); sqlCommand.Parameters["@Status"].Value = "O"; // Add the return value for the stored procedure, which is the order ID. sqlCommand.Parameters.Add(new SqlParameter("@RC", SqlDbType.Int)); sqlCommand.Parameters["@RC"].Direction = ParameterDirection.ReturnValue; try { //Open connection. connection.Open(); // Run the stored procedure. sqlCommand.ExecuteNonQuery(); // Display the order number. this.orderID = (int)sqlCommand.Parameters["@RC"].Value; MessageBox.Show("Order number " + this.orderID + " has been submitted."); } catch { MessageBox.Show("Order could not be placed."); } finally { connection.Close(); } } } } } /// <summary> /// Clears the form data so another new account can be created. /// </summary> private void btnAddAnotherAccount_Click(object sender, EventArgs e) { this.ClearForm(); } /// <summary> /// Closes the form/dialog box. /// </summary> private void btnAddFinish_Click(object sender, EventArgs e) { this.Close(); }
FillOrCancel 양식
FillOrCancel 양식은 주문 ID를 입력한 다음 주문 찾기 단추를 선택할 때 주문을 반환하는 쿼리를 실행합니다. 반환된 행이 읽기 전용 데이터 표에 표시됩니다. 주문 취소 단추를 선택하면 주문을 취소됨(X)으로 표시하거나 주문 채우기 단추를 선택하면 주문을 채워진 순서(F)로 표시할 수 있습니다. 주문 찾기 단추를 다시 선택하면 업데이트된 행이 나타납니다.
FillOrCancel 양식에 대한 자동 생성된 이벤트 처리기 만들기
단추를 두 번 클릭하여 FillOrCancel 양식의 4개 단추에 대해 빈 Click 이벤트 처리기를 만듭니다. 단추를 두 번 클릭하면 디자이너 코드 파일에 자동으로 생성된 코드가 추가되어 단추 선택 시 이벤트가 발생합니다.
FillOrCancel 양식 논리에 대한 코드 추가
FillOrCancel 양식 논리를 완료하려면 다음 단계를 수행합니다.
멤버의 이름을 정규화할 필요가 없도록 다음 두 네임스페이스를 범위로 가져옵니다.
클래스에 변수 및 도우미 메서드를 추가합니다.
// Storage for the order ID value. private int parsedOrderID; /// <summary> /// Verifies that an order ID is present and contains valid characters. /// </summary> private bool IsOrderIDValid() { // Check for input in the Order ID text box. if (txtOrderID.Text == "") { MessageBox.Show("Please specify the Order ID."); return false; } // Check for characters other than integers. else if (Regex.IsMatch(txtOrderID.Text, @"^\D*$")) { // Show message and clear input. MessageBox.Show("Customer ID must contain only numbers."); txtOrderID.Clear(); return false; } else { // Convert the text in the text box to an integer to send to the database. parsedOrderID = Int32.Parse(txtOrderID.Text); return true; } }
단추 선택 이벤트 처리기 4개에 대한 메서드 본문을 완료합니다.
/// <summary> /// Executes a t-SQL SELECT statement to obtain order data for a specified /// order ID, then displays it in the DataGridView on the form. /// </summary> private void btnFindByOrderID_Click(object sender, EventArgs e) { if (IsOrderIDValid()) { using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString)) { // Define a t-SQL query string that has a parameter for orderID. const string sql = "SELECT * FROM Sales.Orders WHERE orderID = @orderID"; // Create a SqlCommand object. using (SqlCommand sqlCommand = new SqlCommand(sql, connection)) { // Define the @orderID parameter and set its value. sqlCommand.Parameters.Add(new SqlParameter("@orderID", SqlDbType.Int)); sqlCommand.Parameters["@orderID"].Value = parsedOrderID; try { connection.Open(); // Run the query by calling ExecuteReader(). using (SqlDataReader dataReader = sqlCommand.ExecuteReader()) { // Create a data table to hold the retrieved data. DataTable dataTable = new DataTable(); // Load the data from SqlDataReader into the data table. dataTable.Load(dataReader); // Display the data from the data table in the data grid view. this.dgvCustomerOrders.DataSource = dataTable; // Close the SqlDataReader. dataReader.Close(); } } catch { MessageBox.Show("The requested order could not be loaded into the form."); } finally { // Close the connection. connection.Close(); } } } } } /// <summary> /// Cancels an order by calling the Sales.uspCancelOrder /// stored procedure on the database. /// </summary> private void btnCancelOrder_Click(object sender, EventArgs e) { if (IsOrderIDValid()) { // Create the connection. using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString)) { // Create the SqlCommand object and identify it as a stored procedure. using (SqlCommand sqlCommand = new SqlCommand("Sales.uspCancelOrder", connection)) { sqlCommand.CommandType = CommandType.StoredProcedure; // Add the order ID input parameter for the stored procedure. sqlCommand.Parameters.Add(new SqlParameter("@orderID", SqlDbType.Int)); sqlCommand.Parameters["@orderID"].Value = parsedOrderID; try { // Open the connection. connection.Open(); // Run the command to execute the stored procedure. sqlCommand.ExecuteNonQuery(); } catch { MessageBox.Show("The cancel operation was not completed."); } finally { // Close connection. connection.Close(); } } } } } /// <summary> /// Fills an order by calling the Sales.uspFillOrder stored /// procedure on the database. /// </summary> private void btnFillOrder_Click(object sender, EventArgs e) { if (IsOrderIDValid()) { // Create the connection. using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString)) { // Create command and identify it as a stored procedure. using (SqlCommand sqlCommand = new SqlCommand("Sales.uspFillOrder", connection)) { sqlCommand.CommandType = CommandType.StoredProcedure; // Add the order ID input parameter for the stored procedure. sqlCommand.Parameters.Add(new SqlParameter("@orderID", SqlDbType.Int)); sqlCommand.Parameters["@orderID"].Value = parsedOrderID; // Add the filled date input parameter for the stored procedure. sqlCommand.Parameters.Add(new SqlParameter("@FilledDate", SqlDbType.DateTime, 8)); sqlCommand.Parameters["@FilledDate"].Value = dtpFillDate.Value; try { connection.Open(); // Execute the stored procedure. sqlCommand.ExecuteNonQuery(); } catch { MessageBox.Show("The fill operation was not completed."); } finally { // Close the connection. connection.Close(); } } } } } /// <summary> /// Closes the form. /// </summary> private void btnFinishUpdates_Click(object sender, EventArgs e) { this.Close(); }
애플리케이션 테스트
애플리케이션을 실행하고 몇 가지 고객 및 주문을 만들어 모든 것이 예상대로 작동하는지 확인합니다.
데이터베이스가 변경 내용으로 업데이트되었는지 확인하려면 다음을 수행합니다.
서버 탐색기에서 테이블 노드를 엽니다.
고객 및 주문 노드를 마우스 오른쪽 단추로 클릭하고 테이블 데이터 표시를 선택합니다.