在 Visual Studio 和 SQL 服务器数据库中使用 Vb.Net 创建搜索功能
Creating Search Function using Vb.Net in Visual Studio and SQL Server database
我正在寻求帮助,以创建一个函数来对我在 SQL 服务器上的数据库进行排序,我可以在其中搜索名称和部件号。我的数据库已连接到 visual studio,但很难在代码中连接到数据库并能够在数据网格视图上生成数据库。
有什么帮助,谢谢
您需要实施几个概念:
- 连接到数据库
- 使用必要的
WHERE
子句设置您的 SQL 命令
- 用结果填充数据表
- 将 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
我正在寻求帮助,以创建一个函数来对我在 SQL 服务器上的数据库进行排序,我可以在其中搜索名称和部件号。我的数据库已连接到 visual studio,但很难在代码中连接到数据库并能够在数据网格视图上生成数据库。
有什么帮助,谢谢
您需要实施几个概念:
- 连接到数据库
- 使用必要的
WHERE
子句设置您的 SQL 命令 - 用结果填充数据表
- 将 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