【问题标题】:Select Query on Access Database in Visual Studio在 Visual Studio 中选择对 Access 数据库的查询
【发布时间】:2013-05-23 00:41:12
【问题描述】:

这是我的代码:

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

    ltRooms.Text = CInt(Session("numOfRooms"))


    'Calculate total cost
    Dim intPrice As Integer
    Dim intTotal As Integer

    intPrice = AccessDataSource1.SelectCommand = "SELECT [Price] FROM [Rooms] WHERE ([RoomType] = 'RoomType')"


    intTotal = intPrice * intRooms
    ltPrice.Text = intTotal.ToString

    End Sub

和我的数据源

           <asp:AccessDataSource ID="AccessDataSource1" runat="server" 
        DataFile="Hostel.accdb" 
        SelectCommand="SELECT * FROM [Bookings]"></asp:AccessDataSource>

我正在尝试存储来自选择查询的值,然后使用它来计算总价,然后将其存储在文字中。到目前为止,我只得到 0。没有编译错误。

有人知道为什么这不起作用吗?

【问题讨论】:

  • SelectCommand 返回的 intPrice 的值是多少?如果它是错误的,那么我会检查传递给查询的 RoomType 的值。
  • 它的值为 0,因此它甚至没有从数据库中检索值。
  • RoomType 是一个字符串变量,这是将变量传递给 select 语句的正确方法吗?
  • 我认为您需要将 SelectCommand 格式化为:“SELECT [Price] FROM [Rooms] WHERE ([RoomType] = '" & RoomType & "')”。如果您在以“intTotal =”开头的行上设置断点并运行应用程序,您应该能够看到 SQL 查询是什么。
  • 为评论欢呼,仍然得到 0。我也设置了一个断点,但不会给我想要的信息。

标签: asp.net sql visual-studio-2010 ms-access select


【解决方案1】:

为了清楚起见,我将各种 cmet 合并为一个答案,并停止页面抱怨扩展讨论。这完全不在我的脑海中,因此代码中可能存在一些错误。不过,这应该足以查明问题。

首先,今天我再看一遍,我认为您的代码只是设置了数据源的SelectCommand 属性,并没有真正查询数据库。我认为您需要使用DataSource.Select 方法。

您的代码最终可能看起来像这样:

AccessDataSource1.SelectCommand = "SELECT [Price] FROM [Rooms] WHERE ([RoomType] = '" & RoomType & "')"

Dim intPrices As List(Of Integer) = AccessDataSource1.Select(DataSourceSelectArguments.Empty)

' Now do stuff with your price data.

如果上述方法没有帮助,那么我将检查 Select 调用返回的 intPrice 的值。您还应该检查 RoomType 是否设置正确。

如果从数据库返回错误的数据,那么您应该能够修复 SQL 查询以检索正确的数据。如果您需要进一步的帮助,请发布 SQL 查询和表结构。

如果返回正确的数据,则检查intRooms 的定义位置。如果它为零,那么无论intPrice 的值如何,您的总数都将计算为零。

【讨论】:

  • 你说得对,我也需要 DataSource.Selected 方法。感谢您的所有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2019-03-16
  • 1970-01-01
相关资源
最近更新 更多