【问题标题】:Creating Search Function using Vb.Net in Visual Studio and SQL Server database在 Visual Studio 和 SQL Server 数据库中使用 Vb.Net 创建搜索函数
【发布时间】:2022-01-24 00:34:45
【问题描述】:

我正在寻求帮助,以创建一个函数来对我在 SQL Server 上的数据库进行排序,我可以在其中搜索名称和部件号。我将我的数据库连接到了 Visual Studio,但在代码中连接到数据库并且能够在数据网格视图上生成数据库时遇到了困难。

任何帮助,谢谢

【问题讨论】:

标签: sql-server database vb.net visual-studio


【解决方案1】:

您需要实现几个概念:

  1. 连接到数据库
  2. 使用必要的WHERE 子句设置您的 SQL 命令
  3. 用结果填充数据表
  4. 将 DataTable 绑定到 DataGridView

这是一个示例,我已经对代码进行了大量注释以解释发生了什么:

' wrap code in Try/Catch because database operations can fail
Try
    ' create a new instance of the connection object
    Using connection = New SqlConnection("My Connection String Here")

        ' create a new instance of the command object
        Using command = New SqlCommand("Select * From MyTable WHERE Name = @name AND PartNumber = @part", connection)
            ' parameterize the query
            command.Parameters.Add("@name", SqlDbType.VarChar, 100).Value = "my name search"
            command.Parameters.Add("@part", SqlDbType.VarChar, 100).Value = "my part number search"

            ' open the connection
            connection.Open()

            ' create a new instance of the data adapter object
            Using adapter = New SqlDataAdapter(command)
                ' fill a DataTable with the data from the adapter
                Dim table = New DataTable()
                adapter.Fill(table)

                ' bind the DataTable to the DataGridView
                MyDataGridView.DataSource = table
            End Using

            ' close the connection
            connection.Close()
        End Using ' disposal of command
    End Using ' disposal of connection
Catch ex As Exception
    ' display the error
    MessageBox.Show(ex.Message)
End Try

【讨论】:

  • @PasskyyCode 注意正确使用Using来处理所有对象,正确使用参数化,指定参数类型和长度,尽可能晚地打开连接,捕获并显示异常 关闭连接后。您通常应该避免使用SELECT *,而是指定您想要的所有列
  • 使用adapter.Fill方法时不必调用connection.Open()/connection.Close()。它会自动为您执行这些操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多