【问题标题】:Writing VB.Net code for filtering SQL Server table properties编写用于过滤 SQL Server 表属性的 VB.Net 代码
【发布时间】:2019-12-31 16:31:17
【问题描述】:

我的 SQL Server 表中有几列,并且想要过滤“承包商”列。在“承包商”列中,用户可以选择两个名称“Namal”和“其他”,如屏幕截图所示。

我想要的是只为“Namal”而不是“其他”获得“金额”的总和

这是我编写但无法正常工作的代码。这里@d1@d2 是用户可以选择的日期范围。

Imports System.Data.SqlClient
Public Class Form6
    Dim connection As New SqlConnection("server=(local); Database=Luminex; integrated security=true")

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim table As New DataTable()
        Dim command As New SqlCommand("select sum(Amount) as a  from PeoTVDB where Date between @d1 and @d2 and Contractor= @Namal", connection)

        command.Parameters.Add("@d1", SqlDbType.Date).Value = DateTimePicker1.Value
        command.Parameters.Add("@d2", SqlDbType.Date).Value = DateTimePicker2.Value

        Dim adapter As New SqlDataAdapter(command)
        adapter.Fill(table)

        Label1.Text = table.Rows(0)("a").ToString()    

    End Sub        
End Class

【问题讨论】:

  • 您为这个问题添加了几个不相关的标签,包括 C# 和 MySQL。请在以后的问题中使用正确的标签。
  • 你也说我写的代码不行。它怎么行不通?您遇到的问题是什么。您也没有将namal 参数添加到SqlCommand
  • 很难解释我的问题,但管理员允许我发布一些截图,我可以进一步解释
  • 在此处粘贴 cmets 中的链接,我会将它们放入您的问题中。澄清一下,我不是管理员或版主
  • 正如其他人提到的,参数@Namal 是如何填充的?

标签: sql-server vb.net


【解决方案1】:

将数据库对象保留在使用它们的方法的本地。如果您在多个地方使用连接字符串,则将其放置为类级别变量。

数据库对象需要关闭和处置。即使出现错误,Using...End Using 块也会为您处理此问题。

我认为 Date 可能是 Sql Server 中的保留字,所以我用括号对其进行了转义。即使不保留也不会伤害任何东西。

我很高兴看到Parameters.Add 方法。唯一的问题是你忘记了一个。我不得不猜测类型和值是什么。

由于您只请求一条数据,您可以使用.ExecuteScalar,它返回一个对象,因此CDec()

Private ConString As String = "server=(local); Database=Luminex; integrated security=true"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Amount As Decimal
    Using connection As New SqlConnection(ConString),
        command As New SqlCommand("select COALESCE(sum(Amount), 0) as a  from PeoTVDB where [Date] between @d1 and @d2 and Contractor= @Namal", connection)
        command.Parameters.Add("@d1", SqlDbType.Date).Value = DateTimePicker1.Value
        command.Parameters.Add("@d2", SqlDbType.Date).Value = DateTimePicker2.Value
        command.Parameters.Add("@Namal", SqlDbType.NVarChar, 200).Value = "Some Value"
        connection.Open()
        Amount = CDec(command.ExecuteScalar)
    End Using
    Label1.Text = Amount.ToString
End Sub

【讨论】:

  • 您应该考虑 ExecuteScalar 返回 Nothing 的情况,例如Dim amount as Decimal ...其他代码... conn.Open() Dim result As Object = cmd.ExecuteScalar() conn.Close() If result IsNot Nothing Then amount = CDec(result) End If。如果你真的想;)
  • @AndrewMorton 我在选择查询中添加了 COALESCE(sum(Amount), 0) 来处理空值。没有 conn.Close End Using 句柄。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多