VB.NET怎么访问数据库

2024-12-01 07:23:58
推荐回答(3个)
回答1:

以下示例代码来自msdn
Option Explicit On
Option Strict On

Imports System
Imports System.Data
Imports System.Data.SqlClient

Public Class Program
Public Shared Sub Main()

Dim connectionString As String = _
"Data Source=(local);Initial Catalog=Northwind;" _
& "Integrated Security=true"

' Provide the query string with a parameter placeholder.
Dim queryString As String = _
"SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
& "WHERE UnitPrice > @pricePoint " _
& "ORDER BY UnitPrice DESC;"

' Specify the parameter value.
Dim paramValue As Integer = 5

' Create and open the connection in a using block. This
' ensures that all resources will be closed and disposed
' when the code exits.
Using connection As New SqlConnection(connectionString)

' Create the Command and Parameter objects.
Dim command As New SqlCommand(queryString, connection)
command.Parameters.AddWithValue("@pricePoint", paramValue)

' Open the connection in a try/catch block.
' Create and execute the DataReader, writing the result
' set to the console window.
Try
connection.Open()
Dim dataReader As SqlDataReader = _
command.ExecuteReader()
Do While dataReader.Read()
Console.WriteLine( _
vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}", _
dataReader(0), dataReader(1), dataReader(2))
Loop
dataReader.Close()

Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Using
End Sub
End Class
----------------------回答补充------------------------------------
上面的源码你应该仔细看看,因为这是微软的示例代码,是通用的,写得很规范。
至于你的特殊的问题,在vb2010中可以不用一句代码把你的表显示在窗体上。

回答2:

leiyangbdwk说得对。

回答3:

使用 ADO.NET 里的方法。 MSDN里搜索ADO.NET,即可找到你要的。