简介:VB.NET数据库访问涉及使用Visual Basic .NET语言与各种数据库系统(如SQL Server, Access)进行交互的技术和方法。通过ADO.NET等技术,开发者能够高效地执行查询、管理数据集及处理事务。
VB.NET提供了多种方式来访问数据库,包括使用ADO.NET、LINQ to SQL以及Entity Framework等技术。下面是一些简单的示例代码:
1. 使用ADO.NET连接SQL Server并执行查询:
```vb.net
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connectionString As String = Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Using connection As New SqlConnection(connectionString)
Try
connection.Open()
Console.WriteLine(Connection opened.)
创建命令对象以执行SQL查询。
Dim command As SqlCommand = connection.CreateCommand()
command.CommandText = SELECT * FROM MyTable
执行查询并获取结果集。
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine({0} {1}, reader(0), reader(1))
End While
Catch ex As Exception
Console.WriteLine(An error occurred: & ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
End Module
```
2. 使用LINQ to SQL创建数据模型并执行查询:
```vb.net
Imports System.Data.Linq
Module Module1
Sub Main()
创建数据库上下文对象。
Dim db As New DataContext(Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;)
获取表的映射类型(假设已经生成了MyTable类)。
Dim table = TryCast(db.GetTable(Of MyTable)(), Table(Of MyTable))
If table IsNot Nothing Then
For Each row In From r In table Select r
Console.WriteLine({0} {1}, row.Field1, row.Field2)
Next
End If
End Sub
End Module
```
这些示例展示了如何使用VB.NET进行基本的数据库访问操作。根据具体需求,可以选择适合的技术和方法来实现更复杂的功能。