vb.net数据库应用 vb数据库操作实例( 四 )


Catch er As Exception
MsgBox(er.ToString)
Return False
End Try
myDataSet.Tables.Remove(TableName)
Return True
End Function
@#更新物理表的一个字段的值 。strSql:查询语句,FieldName_Value:字段及与对应的值
Public Overloads Sub Update(ByVal strSql As String, ByVal FieldName_Value As String)
Dim myDataAdapter As New OleDbDataAdapter()
Dim myDataSet As New DataSet()
Dim dRow As DataRow
Dim TableName, FieldName As String
Dim Value As Object
Dim a() As String
a = strSql.Split(" ")
TableName = a(3)
a = FieldName_Value.Split("=")
FieldName = a(0).Trim
Value = https://www.04ip.com/post/a(1)
myDataAdapter.SelectCommand = New OleDbCommand(strSql, mOleCnnDB)
Dim custCB As OleDbCommandBuilder = New OleDbCommandBuilder(myDataAdapter)
myDataSet.Tables.Add(TableName)
myDataAdapter.Fill(myDataSet, TableName)
dRow = myDataSet.Tables(TableName).Rows(0)
If ValueNothing Then
dRow.Item(FieldName) = Value
End If
Try
myDataAdapter.Update(myDataSet, TableName)
myDataSet.Tables.Remove(TableName)
Catch er As Exception
MsgBox(er.ToString)
End Try
End Sub
@#删除物理表的数据 。TableName:表名,strWhere:条件
Public Overloads Sub Delete(ByVal TableName As String, ByVal strWhere As String)
Dim myReader As OleDbDataReader
Dim myCommand As New OleDbCommand()
Dim strSql As String
strSql = "delete FROM "TableName" where "strWhere
myCommand.Connection = mOleCnnDB
myCommand.CommandText = strSql
Try
myReader = myCommand.ExecuteReader()
myReader.Close()
Catch er As Exception
MsgBox(er.ToString)
End Try
End Sub
End Class
定义一操作数据库中物理表的类CData,此类继承CDataBase,即:
Public Class CData:Inherits CDataBase
此类应该由供用户提供所操作的物理表的表名,指定了表名就可取得该表的所有性质 。该表主要完成插入、删除、更新功能 。定义其属性、方法如下:
申明类CData的变量:
@#所要操作的表名
Private Shared UpdateTableName As String
@#所要操作的表对象
Public Shared UpdateDataTable As New DataTable()
@#对应表的一行数据197
Public Shared ObjFields() As Object
@#表的字段数
Public Shared FieldCount As Int16
@#主关键字 。我们假设每个物理表都有一个主关键字字段fSystemID
Public Shared SystemID As String
说明:Shared 关键字指示一个或多个被声明的编程元素将被共享 。共享元素不关联于某类或结构的特定实例 。可以通过使用类名或结构名称或者类或结构的特定实例的变量名称限定共享元素来访问它们 。
申明类CData的属性UpdateTable,当向UpdateTable赋给了一个已知表的表名,就可确定表的字段数,定义出数据行 。这里,先打开表 , 再重新定义数据行.
Public Property UpdateTable() As String
Get
UpdateTable = UpdateTableName
End Get
Set(ByVal Value As String)
UpdateTableName = Value.Trim
UpdateDataTable = DB.GetDataTable(UpdateTableName)
UpdateTableFieldNames = UpdateDataTable.Clone
FieldCount = UpdateDataTable.Columns.Count
ReDim ObjFields(FieldCount - 1)
End Set
End Property
@#删除由主关键值fSystemID指定的数据行
Public Sub Delete()
Dim strSQL As String
strSQL = "Delete from "UpdateTableName" where fSystemID="SystemID
DB.Delete(strSQL)
UpdateDataTable.Rows.Remove(GetRow)
End Sub
@#向表UpdateTableName中插入一行数据 。数据由ObjFields给出
Public Function Insert() As Boolean
DB.Insert(UpdateTableName, ObjFields)

推荐阅读