database 从 SQL 检索 VB 中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14529534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:51:13  来源:igfitidea点击:

retrieving data in VB from SQL

databasevb.netsql-server-2008

提问by morgred

I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.

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

What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.

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

What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:

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

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

回答by codingbiz

1) Create your connection string

1)创建您的连接字符串

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

2) Connect to your Database

2)连接到您的数据库

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

3) Create a Command and the query

3)创建命令和查询

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

4) Retrieve your result. There are several ways

4) 检索您的结果。有几种方式

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

'Close the connection
connection.Close()

5) Bind to your list box

5)绑定到您的列表框

myListBox.ItemSource = dt

Full code here

完整代码在这里

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

For more info

欲了解更多信息

回答by Sam Axe

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()