vb.net에서 dbnull 데이터 처리
MS-Access 데이터베이스에서 검색하고 DataTable 개체 / 변수, myDataTable에 저장된 데이터의 형식화 된 출력을 생성하고 싶습니다. 그러나 myDataTable의 일부 필드는 dbNull 데이터를 포함합니다. 그래서, 다음과 같은 VB.net 코드 조각은 모든 필드의 값이 경우 오류를 줄 것이다 성 , intials을 , 또는 시드 입니다 DBNULL .
dim myDataTable as DataTable
dim tmpStr as String
dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
tmpStr = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID")=sID Then
' Do something
End If
' print tmpStr
Next
그렇다면 이 질문 에서와 같이 데이터가 dbNull인지 매번 확인할 필요없이 필드에 dbNull 이 포함될 수있을 때 위의 코드가 작동하도록 어떻게합니까?
내가 아는 유일한 방법은 그것을 테스트하는 것입니다. 쉽게 만들려면 결합하여 할 수 있습니다.
If NOT IsDbNull(myItem("sID")) AndAlso myItem("sID") = sId Then
'Do success
ELSE
'Failure
End If
나는 VB로 썼다. 비록 당신이 언어를 혼합 했음에도 불구하고 당신이 필요로하는 것처럼 보인다.
편집하다
IsDbNull을 사용하여 더 읽기 쉽게 정리했습니다.
이 문제를 다루는 데 지쳐서 나를 돕기 위해 NotNull () 함수를 작성했습니다.
Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T
If Value Is Nothing OrElse IsDBNull(Value) Then
Return DefaultValue
Else
Return Value
End If
End Function
용법:
If NotNull(myItem("sID"), "") = sID Then
' Do something
End If
내 NotNull () 함수는 수년에 걸쳐 몇 가지 정밀 검사를 거쳤습니다. Generics 이전에는 모든 것을 Object로 지정했습니다. 그러나 나는 Generic 버전을 훨씬 선호합니다.
Convert.ToString () 및 Convert.ToInteger () 메서드를 사용하여 DB null이있는 항목을 효과적으로 변환 할 수도 있습니다.
Steve Wortham의 코드 에 대한 변형으로 , 명목상 nullable유형 과 함께 사용됩니다 .
Private Shared Function GetNullable(Of T)(dataobj As Object) As T
If Convert.IsDBNull(dataobj) Then
Return Nothing
Else
Return CType(dataobj, T)
End If
End Function
예 :
mynullable = GetNullable(Of Integer?)(myobj)
당신이 할 수있는 다음 쿼리 mynullable(예 mynullable.HasValue)
Microsoft는 데이터베이스 NULL을 나타 내기 위해 .NET 1.0에서 DBNull을 제안했습니다. 그러나 진짜 값이나 null을 저장하기 위해 강력한 형식의 변수를 만들 수 없기 때문에 사용하기가 어렵습니다. Microsoft는 nullable 형식을 사용하여 .NET 2.0에서이 문제를 해결했습니다. 그러나 DBNull을 사용하는 대규모 API 청크가 여전히 남아 있으며 변경할 수 없습니다.
단지 제안이지만 일반적으로하는 일은 다음과 같습니다.
- 데이터베이스에서 읽거나 데이터베이스에 기록 된 데이터를 포함하는 모든 변수는 null 값을 처리 할 수 있어야합니다. 값 유형의 경우 이는 Nullable (Of T)로 만드는 것을 의미합니다. 참조 유형 (String 및 Byte ())의 경우 이는 값이 Nothing이되도록 허용 함을 의미합니다.
- Write a set of functions to convert back and forth between "object that may contain DBNull" and "nullable .NET variable". Wrap all calls to DBNull-style APIs in these functions, then pretend that DBNull doesn't exist.
If you are using a BLL/DAL setup try the iif when reading into the object in the DAL
While reader.Read()
colDropdownListNames.Add(New DDLItem( _
CType(reader("rid"), Integer), _
CType(reader("Item_Status"), String), _
CType(reader("Text_Show"), String), _
CType( IIf(IsDBNull(reader("Text_Use")), "", reader("Text_Use")) , String), _
CType(reader("Text_SystemOnly"), String), _
CType(reader("Parent_rid"), Integer)))
End While
You can use the IsDbNull function:
If IsDbNull(myItem("sID")) = False AndAlso myItem("sID")==sID Then
// Do something
End If
For the rows containing strings, I can convert them to strings as in changing
tmpStr = nameItem("lastname") + " " + nameItem("initials")
to
tmpStr = myItem("lastname").toString + " " + myItem("intials").toString
For the comparison in the if statement myItem("sID")=sID, it needs to be change to
myItem("sID").Equals(sID)
Then the code will run without any runtime errors due to vbNull data.
VB.Net
========
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Call conecDB() 'Connection to Database
da.SelectCommand = New SqlCommand("select max(RefNo) from BaseData", connDB)
da.Fill(dt)
If dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) = "" Then
MsgBox("datbase is null")
ElseIf dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) <> "" Then
MsgBox("datbase have value")
End If
Hello Friends
This is the shortest method to check db Null in DataGrid and convert to string
- create the cell validating event and write this code
- If Convert.ToString(dgv.CurrentCell.Value) = "" Then
- CurrentCell.Value = ""
- End If
This is BY FAR the easiest way to convert DBNull to a string. The trick is that you CANNOT use the TRIM function (which was my initial problem) when referring to the fields from the database:
BEFORE (produced error msg):
Me.txtProvNum.Text = IIf(Convert.IsDBNull(TRIM(myReader("Prov_Num"))), "", TRIM(myReader("Prov_Num")))
AFTER (no more error msg :-) ):
Me.txtProvNum.Text = IIf(Convert.IsDBNull(myReader("Prov_Num")), "", myReader("Prov_Num"))
I think this should be much easier to use:
select ISNULL(sum(field),0) from tablename
Copied from: http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ
참고URL : https://stackoverflow.com/questions/222834/handling-dbnull-data-in-vb-net
'IT TIP' 카테고리의 다른 글
| Android Studio에서 Darcula의 테마를 기본값으로 되 돌리는 방법 (0) | 2020.10.25 |
|---|---|
| Yarn Ubuntu 16.04 (Linux Mint 18.1) 설치 (0) | 2020.10.25 |
| 설치시에만 사용자 지정 작업을 실행하는 방법 (제거 아님) (0) | 2020.10.25 |
| Java에서 여러 수신자에게 메일 보내기 (0) | 2020.10.25 |
| 연관 배열을 PHP에서 값의 간단한 배열로 변환 (0) | 2020.10.25 |