1단계: 전략 인터페이스 정의
먼저 다양한 데이터베이스 전략으로 구현될 GetDataTable 메서드를 선언하는 ISQLStrategy 인터페이스를 만듭니다.
using System.Data; namespace MyProject.Util { public interface ISQLStrategy { DataTable GetDataTable(string sql); } }
2단계: 구체적인 전략 구현
다음으로 각 데이터베이스 유형(MySQL, PostgreSQL 및 SQL Server)에 대한 ISQLStrategy 인터페이스를 구현합니다.
MySQL 전략:
using MySql.Data.MySqlClient; using System; using System.Configuration; using System.Data; namespace MyProject.Util { public class MySQLQuery : ISQLStrategy { public DataTable GetDataTable(string sql) { try { using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.AppSettings["MySqlConnectionString"])) { DataTable dt = new DataTable(); conn.Open(); MySqlCommand command = new MySqlCommand(sql, conn); dt.Load(command.ExecuteReader()); conn.Close(); return dt; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } } }
PostgreSQL 전략:
using Npgsql; using System; using System.Configuration; using System.Data; namespace MyProject.Util { public class NpgSqlQuery : ISQLStrategy { public DataTable GetDataTable(string sql) { try { using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.AppSettings["NpgSqlConnectionString"])) { DataTable dt = new DataTable(); conn.Open(); NpgsqlCommand command = new NpgsqlCommand(sql, conn); NpgsqlDataAdapter _dap = new NpgsqlDataAdapter(command); _dap.Fill(dt); conn.Close(); return dt; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } } }
SQL 서버 전략:
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace MyProject.Util { public class TSqlQuery : ISQLStrategy { public DataTable GetDataTable(string sql) { try { using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["TSqlConnectionString"])) { DataTable dt = new DataTable(); conn.Open(); SqlCommand command = new SqlCommand(sql, conn); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); conn.Close(); return dt; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } } }
3단계: 컨텍스트 클래스 생성
SQLStrategy 클래스는 ISQLStrategy 인스턴스를 사용하여 데이터베이스 작업을 수행합니다.
using System.Data; namespace MyProject.Util { public class SQLStrategy { private readonly ISQLStrategy _sqlStrategy; public SQLStrategy(ISQLStrategy sqlStrategy) { _sqlStrategy = sqlStrategy; } public DataTable GetDataTable(string sql) { return _sqlStrategy.GetDataTable(sql); } } }
4단계: 클라이언트 코드 구현
마지막으로 전략 패턴 구현을 테스트하기 위한 클라이언트 코드를 작성합니다.
using System; using System.Data; namespace MyProject.Util { public class Client { public static void Main() { SQLStrategy sqlHelper = new(new TSqlQuery()); DataTable result = sqlHelper.GetDataTable("SELECT TOP (10) * FROM [Product]"); foreach (DataRow row in result.Rows) { foreach (DataColumn column in result.Columns) { Console.Write($"{column.ColumnName}: {row[column]} \t"); } Console.WriteLine(); } } } }
요약
풀코딩
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using Npgsql; using MySql.Data.MySqlClient; namespace MyProject.Util { //Strategy (Interface) public interface ISQLStrategy { DataTable GetDataTable(string sql); //You could add more methods for "Create", "Update" as well } //Concrete Strategies public class MySQLQuery : ISQLStrategy { public DataTable GetDataTable(string sql) { try { using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.AppSettings["MySqlConnectionString"])) { DataTable dt = new DataTable(); conn.Open(); MySqlCommand command = new MySqlCommand(sql, conn); dt.Load(command.ExecuteReader()); conn.Close(); return dt; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } } public class NpgSqlQuery : ISQLStrategy { public DataTable GetDataTable(string sql) { try { using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.AppSettings["NpgSqlConnectionString"])) { DataTable dt = new DataTable(); conn.Open(); NpgsqlCommand command = new NpgsqlCommand(sql, conn); NpgsqlDataAdapter _dap = new NpgsqlDataAdapter(command); _dap.Fill(dt); conn.Close(); return dt; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } } public class TSqlQuery : ISQLStrategy { public DataTable GetDataTable(string sql) { try { using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["TSqlConnectionString"])) { DataTable dt = new DataTable(); conn.Open(); SqlCommand command = new SqlCommand(sql, conn); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); conn.Close(); return dt; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } } //Context public class SQLStrategy { public ISQLStrategy _sqlStrategy; public SQLStrategy(ISQLStrategy sqlStrategy) { _sqlStrategy = sqlStrategy; } public DataTable GetDataTable(string sql) { return _sqlStrategy.GetDataTable(sql); } } // Testing the Strategy Design Pattern // Client Code public class Client { public static void Main() { SQLStrategy sqlHelper = new(new TSqlQuery()); DataTable result = sqlHelper.GetDataTable("SELECT TOP (10) * FROM [Product]"); foreach (DataRow row in result.Rows) { foreach (DataColumn column in result.Columns) { Console.Write($"{column.ColumnName}: {row[column]} \t"); } Console.WriteLine(); } } } }
C#이 좋아요!
위 내용은 전략 디자인 패턴 단계별 가이드를 사용하여 C#에서 데이터베이스 도우미 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!