DB 열 메타 데이터를 처리하는 클래스가 있습니다. 클래스의 프로퍼티 중 하나가 해당 테이블입니다. 이것은 생성자를 통해 객체에 전달됩니다. 또한 생성자에서 클래스 내 다른 변수를 할당하는 로직을 적용합니다. 이렇게하려면 DB에 연결하고 테이블에 대해 쿼리하고 변수에 값을 반환하는 여러 개인 메서드가 있습니다.C# DB에서 데이터를 가져 오는 데 사용되는 메서드 수를 줄입니다.
제 문제는 다른 메소드가 많이 있지만 똑같은 일을하고 있지만 다른 데이터 유형을 반환한다는 것입니다. 그래서 예를 들어 내 코드는 다음과 같습니다.
public Column(string tableName)
{
strTableName = tableName;
pkColumnName = GetPKColumnName(tableName);
pkColumnLenght = GetPKColumnLenght(tableName);
}
private string GetPKColumnName(string tableName)
{
string query = String.Format("SELECT myColName FROM myTable where myTableName = {0}", tableName);
string result = "";
try
{
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(query, con))
{
result = (string)command.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
private int GetPKColumnLenght(string tableName)
{
string query = String.Format("SELECT myColLenght FROM myTable where myTableName = {0}", tableName);
int result = 0;
try
{
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(query, con))
{
result = (int)command.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
이렇게 많은 다른 방법이 있습니다. 이것은 나에게 잘 어울리지 않아서, 이런 식으로 최선의 방법이 무엇인지 궁금해하고있었습니다.
반환 유형을 객체로 선언하고 반환 된 값을 변수에 할당 할 때 데이터 유형 변환을 수행해야합니까?
이 질문은 http://codereview.stackexchange.com/ 더 적합 –
"반환 유형을 객체로 선언해야합니까?" 'Name'과'Length'를 캡슐화하고 반환하는 클래스를 정의하십시오. –
SQL 삽입이나 다른 문제를 피하려면 매개 변수 기반 쿼리를 사용해야합니다. https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx – eschneider