我使用Visual Basic 2010和Microsoft SQL Server 2008.我有我的数据库和我的表,我只使用界面在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
答案 0 :(得分:4)
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)绑定到列表框
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
了解更多信息
答案 1 :(得分:0)
SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()