sql-server - 编写用于过滤 SQL Server 表属性的 VB.Net 代码
问题描述
我的 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
解决方案
将数据库对象保留在使用它们的方法的本地。如果您在多个地方使用连接字符串,则将其放置为类级别变量。
数据库对象需要关闭和处置。Using...End Using
即使出现错误,blocks 也会为您解决这个问题。
我认为 Date 可能是 Sql Server 中的保留字,所以我用括号对其进行了转义。即使不保留也不会伤害任何东西。
我很高兴看到Parameters
和.Add
方法。唯一的问题是你忘记了一个。我不得不猜测类型和值是什么。
由于您只请求一条数据,您可以使用.ExecuteScalar
which 返回一个对象,因此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
推荐阅读
- r - 如何反转 t.test() 的组比较顺序?
- rust - 使用泛型类型时的类型转换
- mysql - Laravel 迁移错误:150“外键约束格式不正确”
- swift - 禁用 UITextField“向上”和“向下”箭头的最佳方法
- python - 解压元组的索引对象
- python - 评估结果的质量 // 标准误差或其他一些统计数据
- java - 如何在java中找到符号的代理对
- python - 我如何知道哪个字符在字符串中的某个位置?
- python - Python - 如何通过 openpyxl 或其他模块读取 excel 中的计算公式?
- c# - 如何编写一个返回 xaml 切换开关的值的方法?