[c#] C#으로 데이터베이스에서 데이터 삭제하는 방법

이번 포스트에서는 C# 프로그램으로 데이터베이스에서 데이터를 삭제하는 방법을 다루어 보겠습니다. 데이터베이스 연결, 쿼리 실행, 그리고 데이터 삭제에 대한 기본적인 내용을 다룰 것입니다.

데이터 연결 및 삭제 쿼리 실행

C#에서 데이터베이스를 다루기 위해서는 SqlConnection 클래스를 사용하여 데이터베이스에 연결해야 합니다. 연결을 설정한 후에는 SqlCommand 클래스를 사용하여 삭제 쿼리를 실행할 수 있습니다.

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
        string deleteQuery = "DELETE FROM YourTable WHERE YourCondition";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(deleteQuery, connection))
            {
                connection.Open();
                int rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine($"삭제된 행 수: {rowsAffected}");
            }
        }
    }
}

데이터 삭제 예제

다음은 데이터베이스에서 데이터를 삭제하는 간단한 C# 프로그램 예제입니다. 이 예제는 실제 데이터베이스 연결 정보와 쿼리에 맞게 수정해야 합니다.

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
        string deleteQuery = "DELETE FROM YourTable WHERE YourCondition";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(deleteQuery, connection))
            {
                connection.Open();
                int rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine($"삭제된 행 수: {rowsAffected}");
            }
        }
    }
}

위의 코드에서 connectionString 변수의 값을 실제 데이터베이스 연결 정보로, deleteQuery 변수의 값을 데이터를 삭제할 테이블과 조건에 맞는 삭제 쿼리로 수정해야 합니다.

이제 C#을 사용하여 데이터베이스에서 데이터를 삭제하는 방법에 대해 알아보았습니다. 데이터베이스 연결 및 삭제에 대한 세부 내용은 사용하는 데이터베이스 및 라이브러리에 따라 달라질 수 있으므로 해당 라이브러리의 문서를 참고하는 것이 좋습니다.

참고 자료