[c#] C#에서 데이터베이스 연동 방법

ADO.NET 사용

C#에서 데이터베이스와의 연동을 위해 ADO.NET을 사용할 수 있습니다. ADO.NET을 이용하면 데이터베이스와의 연결, 명령 수행 및 데이터를 처리할 수 있습니다. 다음은 ADO.NET을 사용하여 데이터베이스에 연결하는 간단한 예제입니다.

using System;
using System.Data;
using System.Data.SqlClient;

namespace DatabaseConnection
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                // 데이터베이스 작업 수행
            }
        }
    }
}

위 코드에서 SqlConnection 클래스를 사용하여 데이터베이스에 연결하고, 연결 문자열을 통해 데이터베이스 정보를 제공합니다.

Entity Framework 사용

Entity Framework는 C# 애플리케이션과 데이터베이스 간의 개체 모델을 관리하는 데 사용됩니다. 이를 통해 데이터를 쉽게 검색하고 수정할 수 있습니다. Entity Framework를 사용하려면 먼저 NuGet 패키지 관리자를 사용하여 Entity Framework 패키지를 설치해야 합니다.

using System;
using System.Linq;

namespace DatabaseConnection
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new YourDbContext())
            {
                // 데이터베이스 작업 수행
            }
        }
    }
}

위 코드에서 YourDbContext는 데이터베이스에 대한 모델을 나타내는 클래스입니다.

위에서 언급한 방법들을 통해 C# 애플리케이션에서 데이터베이스와의 연동을 효과적으로 수행할 수 있습니다.

참고 자료