[c#] C#과 데이터베이스 연동을 위한 프로시저 및 함수 호출

C#에서 데이터베이스를 사용하려면 프로시저나 함수를 호출하여 데이터베이스와 상호작용해야 합니다. 이를 위해 .NET Framework에서 제공하는 ADO.NET을 사용하여 데이터베이스와 연동할 수 있습니다. 이 튜토리얼에서는 C#에서 데이터베이스의 프로시저와 함수를 호출하는 방법에 대해 알아보겠습니다.

데이터베이스 연결 설정

먼저, C# 프로젝트에서 데이터베이스에 연결하기 위해 Connection String을 설정해야 합니다. Connection String은 데이터베이스의 위치, 사용자 인증 정보 및 다른 연결 옵션을 포함합니다. 다음은 Connection String의 예시입니다:

string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

이후에는 SqlConnection 클래스를 사용하여 데이터베이스와의 연결을 설정합니다.

프로시저 호출

데이터베이스에 정의된 프로시저를 호출하는 방법은 다음과 같습니다. SqlCommand 클래스를 사용하여 프로시저를 실행합니다.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand("StoredProcedureName", connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        // Add parameters if needed
        // Execute the command
        connection.Open();
        command.ExecuteNonQuery();
    }
}

함수 호출

데이터베이스 함수를 호출하는 방법은 프로시저 호출과 유사합니다. SqlCommand 객체를 생성하고 CommandText에 함수의 이름을 지정하여 CommandType 속성을 StoredProcedure가 아닌 Text로 설정합니다.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand("SELECT dbo.GetCustomerName(1)", connection))
    {
        connection.Open();
        var result = command.ExecuteScalar();
        Console.WriteLine("Customer Name: " + result.ToString());
    }
}

프로시저나 함수의 실행 결과로 반환되는 데이터를 가져올 때에는 ExecuteReader(), ExecuteScalar(), ExecuteNonQuery() 등의 메서드를 사용할 수 있습니다.

마무리

이렇게하면 C# 애플리케이션에서 데이터베이스의 프로시저와 함수를 호출할 수 있습니다. 데이터베이스 연동 시 보안과 예외 처리를 고려해야 합니다. 또한, 코드의 가독성과 유지보수를 위해 분리된 데이터베이스 계층 및 오브젝트 지향적인 방식을 사용하는 것이 좋습니다.

참조: