Datareader Retrieving Data

為{幸葍}努か 提交于 2020-01-30 11:32:34

问题


I have Memberships and Bookings tables in a database containing an attribute cust_id, which is the primary key in Memberships and reference key in Bookings. When I am executing a data reader I want it to read cust_id values from membership table but it is reading it from the bookings table.

Also, when I compare two cust_id values, 1 taken from a textbox and the other taken a from database column, even though both are the same, but the comparison result is false. I have compared using string.equals(str1, str2) and have also compared the two directly using if statement. But in both cases, even if the string is the same, the result is otherwise.

My query is:

 str2 = "select Memberships.cust_id from Memberships, Bookings where   Memberships.cust_id = Bookings.cust_id"
Dim cmd2 As New SqlCommand(str2, con)
con.Open()

Dim bookchk As SqlDataReader = cmd2.ExecuteReader  
While bookchk.Read()
Dim str1 As String = MskdTxtCustId.Text
Dim str3 As String = bookchk("cust_id")
MessageBox.Show(str1 & "," & str3 & String.Equals(str1, str3))

End While
    bookchk.Close()
    con.Close()

回答1:


Try explicitly stating that you want an INNER JOIN instead:

str2 = "select m.cust_id from Memberships AS M " &_
       " INNER JOIN Bookings AS B ON B.cust_id = M.cust_id;"

When comparing, use String.Compare(), and make sure you're trimming whitespace, just in case.

Dim str1 As String = MskdTxtCustId.Text.Trim()
Dim str3 As String = bookchk("cust_id").ToString().Trim()

Dim compareResult As Integer = String.Compare(s1, s2)
MessageBox.Show("compare str1: {0}, str3: {1}, result: {2}" , str1, str3, compareResult)

compareResult = String.Compare(s1, s2, True)
MessageBox.Show("Compare insensitive. result: {0}", compareResult)



回答2:


As for String compare: I always use Datareader.GetString(item) as in this Sub:

    If IsDBNull(Dr.Item(nr)) Then
        Return ""
    Else
        Return Dr.GetString(nr).TrimEnd
    End If

where nr identifies the row to fetch a value from. You are using some default method to convert the database value to the program variable. I rather write what I want.



来源:https://stackoverflow.com/questions/7356709/datareader-retrieving-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!