如何使用VB.NET从SQL服务器读取表中的特定列 [英] How do I read a specific column in a table from SQL sever using VB.NET

查看:99
本文介绍了如何使用VB.NET从SQL服务器读取表中的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阅读一篇特定专栏。这是我的代码。它从Table_DTR读取我的AfternoonTime-In列是否有数据,但它仍然显示Has Rows,即使没有任何内容。我该如何解决这个问题?



我的尝试:



I want to Read a Specific column . this is my code. It Reads my AfternoonTime-In column from Table_DTR whether it has data on it, but it keeps on Displaying "Has Rows" even if there is nothing in . how can I fix this ?

What I have tried:

Connect = New SqlConnection(ConnectionString)
       Connect.Open()

       Dim Query1 As String = "Select  [AfternoonTime-Out] From Table_DTR Where Date = @Date and EmployeeID = @EmpID "
       Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
       cmd1.Parameters.AddWithValue("@Date", DTRform.datetoday.Text)
       cmd1.Parameters.AddWithValue("@EmpID", DTRform.DTRempID.Text)


       Using Reader As SqlDataReader = cmd1.ExecuteReader()
           If Reader.HasRows Then
               MsgBox("Has rows")
               Reader.Close()

           Else
               MsgBox("empty")
           End If
       End Using

推荐答案

如果HasRows属性返回true,则结果集很可能确实有行。但是,最初你没有位于第一行,所以如果你试图获取值,你会得到一个例外。



使用阅读mehtod [ ^ ]在结果集中前进并查看它包含的内容。



为了澄清这种情况,如果你在结果集中包含Date和emplyoeeid列可能会有所帮助。



另请注意,因为日期是一个保留字,列名应该用括号括起来:.. WHERE [Date] = ...



还有一件事。只要满足WHERE条件,结果集将包含行,无论AfternoonTime-Out列是否为值。您可以通过将列与 DBNull.Value [ ^ ]。如果要排除空行,​​则需要修改WHERE子句,例如:

If the HasRows property returns true, the result set most likely really has rows. However, initially you're not positioned in the first row so if you try to fetch the values, you'll get an exception.

Use the Read mehtod[^] to advance in the result set and see what it contains.

To clarify the situation it could be helpful if you include columns Date and emplyoeeid to the result set.

Also notice that since date is a reserved word the column name should be surrounded with brackets: .. WHERE [Date] = ...

And one more thing. The result set will contain rows as long as the WHERE condition is satisfied, regardless if the AfternoonTime-Out column as a value or not. You can see if the column contains a NULL value by comparing it to DBNull.Value [^] in C#. If you want to exclude null rows, you need to modify the WHERE clause, for example:
Dim Query1 As String = "Select  [AfternoonTime-Out] From Table_DTR Where Date = @Date and EmployeeID = @EmpID AND [AfternoonTime-Out] IS NOT NULL"


这篇关于如何使用VB.NET从SQL服务器读取表中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆