SQL 데이터베이스에서 NULL INT/Char를 처리하기위한 모범 사례는 무엇입니까?
-
11-07-2019 - |
문제
사용자의 선택적 프로필 인 데이터베이스가 있습니다. 프로파일에는 문자열, char (m 또는 f) 및 int가 있습니다.
나는 사용자의 성별을 내 프로필 객체의 속성에 넣으려고 시도하는 문제를 해결했으며 응용 프로그램은 반환 된 null 값을 처리하는 방법을 모르기 때문에 충돌합니다.
데이터를 적절한 유형으로 캐스팅하려고 시도했습니다
char sex = (char)dt.Rows[0]["Sex"];
내 문제를 해결하지 못했습니다. 그런 다음 유형을 무효가되고 무효가 될 수있는 것으로 변경하려고 시도했으며 변환 문제를 모두 동일하게 얻었습니다. 내가 찾을 수있는 현재 솔루션은 다음과 같습니다.
object.sex = null;
if(dt.Rows[0]["Sex"] != DBNull.Value)
object.sex = (char)dt.Rows[0]["Sex"];
object.WorkExt = null;
if(dt.Rows[0]["WorkExt"] != DBNull.Value)
object.WorkExt = (int)dt.Rows[0]["WorkExt"];
이 작업을 수행하는 더 간단하거나 더 나은 방법이 있습니까? 아니면 내가 올바른 길을 가고 있습니까?
해결책
로타드의 대답 (사용 Is<ColumnName>Null()
) 타이핑 된 데이터 세트에만 작동합니다.
Unttyped 데이터 세트의 경우 다음 코드의 패턴 중 하나를 사용해야합니다. 이 코드가 결정적이지 않으면 알려 주시면 편집 할 때까지 편집하겠습니다. 이것은 실제로 하나의 정답 만 있어야한다는 매우 일반적인 질문입니다.
using System.
using System.Data;
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("test", typeof (char));
dt.Columns["test"].AllowDBNull = true;
DataRow dr = dt.Rows.Add();
char? test;
try
{
test = (char?)dr["test"];
}
catch (InvalidCastException)
{
Console.WriteLine("Simply casting to a nullable type doesn't work.");
}
test = dr.Field<char?>("test");
if (test == null)
{
Console.WriteLine("The Field extension method in .NET 3.5 converts System.DBNull to null.");
}
test = (dr["test"] is DBNull) ? null : (char?) dr["test"];
if (test == null)
{
Console.WriteLine("Before .NET 3.5, you have to check the type of the column's value.");
}
test = (dr["test"] == DBNull.Value) ? null : (char?) dr["test"];
if (test == null)
{
Console.WriteLine("Comparing the field's value to DBNull.Value is very marginally faster, but takes a bit more code.");
}
// now let's put the data back
try
{
dr["test"] = test;
}
catch (ArgumentException)
{
Console.WriteLine("You can't set nullable columns to null.");
}
dr.SetField("test", test);
if (dr["test"] is DBNull)
{
Console.WriteLine("Again, in .NET 3.5 extension methods make this relatively easy.");
}
dr["test"] = (object)test ?? DBNull.Value;
if (dr["test"] is DBNull)
{
Console.WriteLine("Before .NET 3.5, you can use the null coalescing operator, but note the awful cast required.");
}
Console.ReadLine();
}
}
다른 팁
무효 유형은이 목적을 위해서만 설계되었습니다! '숯으로?' '(char?) 대신
class Foo {
char? sex;
}
Foo object;
object.sex = dt.Rows[0]["Sex"] as char?;
이것에 대한 괜찮은 토론은 다음과 같습니다 DBNULL을 확인한 다음 변수에 할당하는 가장 효율적인 방법?.
DT는 ado.net 2 데이터 테이블입니까? 당신은 다음과 같은 일을 할 수 없습니다.
if(dt.Rows[0].IsSexNull()) {} else {}
? 또한 데이터베이스를 제어한다고 가정하면 문자열보다는 비트를 사용하는 것이 더 합리적이지 않습니까?
어때요 :
internal static T CastTo<T>(object value)
{
return value != DBNull.Value ? (T)value : default(T);
}
그런 다음 다음과 같이 사용하십시오.
return new EquipmentDetails(
CastTo<int>(reader["ID"]),
CastTo<int>(reader["CategoryID"]),
CastTo<string>(reader["Description"]));
등...
나는 당신이했던 것처럼 거의 할 것입니다. 나는 그것을 위해 함수를 쓸 것이다 :
하는 일 :
object.sex = handle(dt.Rows[0]["Sex"]);
그리고 손잡이에서 == dbnull.Value Check를 수행합니다.