【问题标题】:Error in Select query using SQL Server in VB.NET Winforms在 VB.NET Winforms 中使用 SQL Server 选择查询时出错
【发布时间】:2020-02-26 05:07:20
【问题描述】:

这个查询没有返回任何值,也没有导致任何错误:

Dim cmdAs1 As String
Dim daAs1 As SqlClient.SqlDataAdapter
Dim dsAs1 As DataSet
Dim dtAs1 As DataTable

cmdAs1 = "SELECT * FROM [SN_Male_Quest_2018].[dbo].[Section_3] WHERE sub_village_id= '" & sub_village_id & "' and household_id= '" & household_id & "' and hrid= '" & male & "' and hrid= '" & female & "' and hrid= '" & adolscent & "' and hrid= '" & respid & "'"
daAs1 = New SqlClient.SqlDataAdapter(cmdAs1, cnn)
dtAs1 = New DataTable()
dsAs1 = New DataSet()
daAs1.Fill(dsAs1, "Section_3")
dtAs1 = dsAs1.Tables("Section_3")
lbloperator.Text = dtAs1.Rows.Count

If (dtAs1.Rows.Count.Equals(0)) Then

【问题讨论】:

  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看 Little Bobby Tables
  • 如果结果集为空,则数据库中没有与过滤器匹配的记录。这里的所有都是它的。由于您甚至没有费心向我们展示过滤器是什么,您希望我们说什么?我敢打赌,您自己甚至都没有看过 SQL 代码。构建 SQL 代码的 VB 代码不是 SQL 代码。除此之外,不要使用字符串连接将值插入 SQL 代码。始终使用参数。这样您就可以避免各种问题,其中一个问题可能会导致这里出现问题。
  • 顺便说一句,如果您想要的是DataTable,那么只需创建一个DataTableDataSet 毫无意义。 Fill 方法将接受 DataTable 作为参数。另外,Fill 方法返回检索到的记录数,因此无需单独测试DataTable 的行数。最后,虽然使用.Equals(0) 并没有错,但没有人这样做,因为当您可以使用更清晰的= 0 时,这很愚蠢。
  • 您应该检查您的WHERE 条件:and hrid= '" & male & "' and hrid= '" & female & "' and hrid= '" & adolscent & "' and hrid= '" & respid & "'"。不太可能匹配

标签: sql-server vb.net select


【解决方案1】:

将您的连接对象保持在使用它的方法的本地。这使您可以控制它是否关闭和处置。即使有错误,Using...End Using 也会为您阻止。在此示例中,连接和命令都包含在 Using 中。

正如@devio 在 cmets 中提到的,您不能让单个字段等于多个不同的值。我只能假设您的意思是“或”。

始终使用参数。我不得不猜测数据类型和字段大小。请检查您的数据库并相应地调整代码。

Private Sub FillDataTable(sub_village_id As String, household_id As String, male As String, female As String, adolscent As String, respid As String)
    Dim dtAs1 As New DataTable
    Using cn As New SqlConnection("Your connection string"),
            cmd As New SqlCommand("SELECT * FROM [Section_3] WHERE sub_village_id= @villageID and household_id= @householdID and (hrid= @hrIDMale Or hrid= @hrIDFemale Or hrid= @hrIDAdolescent Or hrid= @hrIDResID);", cn)
        With cmd.Parameters
            .Add("@villageID", SqlDbType.VarChar, 100).Value = sub_village_id
            .Add("@householdID", SqlDbType.VarChar, 100).Value = household_id
            .Add("@hrIDMale", SqlDbType.VarChar, 100).Value = male
            .Add("@hrIDFemale", SqlDbType.VarChar, 100).Value = female
            .Add("@hrIDAdolescent", SqlDbType.VarChar, 100).Value = adolscent
            .Add("@hrIDResID", SqlDbType.VarChar, 100).Value = respid
        End With
        cn.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
    lbloperator.Text = dt.Rows.Count.ToString
    If dt.Rows.Count = 0 Then
        'Your code here
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多