一个经典的ADO.NET入门例子

类别:.NET开发 点击:0 评论:0 推荐:

众所周知,ADO.NET相对于ADO的最大优势在于对于数据的更新修改可以在与数据源完全断开联系的情况下进行,然后再把数据更新情况传回到

数据源。这样大大减少了连接过多对于数据库服务器资源的占用。下面是我在《ADO.NET实用指南》这本书上看到的一个例子,比较清楚的讲解

了ADO.NET的使用方法。
Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.Common

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim conn As New SqlConnection("data source=localhost;initial catalog=StudentCourse;" & _
        "User ID=;Password=;")
        Dim ds As New DataSet
        Try
            conn.Open()     '在形成SqlDataAdapter前打开conn
            Dim daAuthors As New SqlDataAdapter("Select * From SC", conn)
            Dim bldr As New SqlCommandBuilder(daAuthors)
            daAuthors.Fill(ds,"SC")
            conn.Close()    '在填充完ds后关闭连接,接着对ds进行操作

            Dim tbl As New DataTable
            tbl = ds.Tables("SC")

            Dim rowVals(3) As Object
            rowVals(0) = "5"
            rowVals(1) = "00003"
            rowVals(2) = "0001"
            rowVals(3) = 99
            Dim insertedRow As DataRow
            insertedRow = tbl.Rows.Add(rowVals) '添加一行

            tbl.Rows(0).Delete()    '删除一行

            tbl.Rows(1).BeginEdit()
            tbl.Rows(1)("score") = 89   '修改一行
            tbl.Rows(1).EndEdit()

            conn.Open()
            daAuthors.Update(ds.Tables("SC"))   '须将结果传回数据源时打开连接,update
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class

本文地址:http://com.8s8s.com/it/it42145.htm