database - 从 SQL 中检索 VB 中的数据

标签 database vb.net sql-server-2008

我使用 Visual Basic 2010 和 Microsoft SQL Server 2008。我有我的数据库和我的表,我只使用接口(interface)在 VB 中建立了连接(至少我认为我做到了)。

我想知道的是如何从数据库中获取数据并将其用于我的 VB 项目。我当然已经在寻找解决方案,但我发现的差异只会让我更加困惑。我需要了解的是检索数据的基础知识、工具/对象和过程。

我现在尝试做的是进行一个简单的选择,并在程序启动时立即将该数据放入列表框中,如下所示:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SqlConnection1.Open()



        SqlConnection1.Close()

    End Sub
End Class

最佳答案

1) 创建连接字符串

Dim connectionString As String = "Data Source=localhost;........."

2) 连接到您的数据库

Dim connection As New SqlConnection(connectionString)
conn.Open()

3) 创建命令和查询

Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader()  //Execute the Query

4) 检索结果。有几种方法

Dim dt As New DataTable()
dt.Load(reader)

'Close the connection
connection.Close()

5) 绑定(bind)到你的列表框

myListBox.ItemSource = dt

完整代码在这里

Using connection As New SqlConnection(connectionString)
    Dim command As New SqlCommand("Select * from Products", connection)
    command.Connection.Open()
    SqlDataReader reader = command.ExecuteReader()
 End Using

获取更多信息

关于database - 从 SQL 中检索 VB 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14529534/

相关文章:

android - 删除表时出现受限 API lint 错误。房间持久性

python - 如何为我的 P2P 租赁市场建立数据库?

vb.net - 如何在运行时动态添加菜单项

VB.NET如何把一段文字变成一行?

SQLSTATE[22P02] : Invalid text representation

c# - 远程MySQL访问耗时较长

sql-server - 人们用什么来单元测试他们的存储过程等

sql - 如何在 SQL 中从 XML 中选择值

vb.net - 在 Visual Basic.NET 中构造对象而不分配它

sql - 存储很多位-我应该使用多列还是单个位域列?