朱瑞芳
摘要:運用VB.NET技術(shù)建立數(shù)據(jù)庫項目通用模塊,并且通過運用listView控件,說明數(shù)據(jù)通用模塊的應用方法,闡述了類的繼承和擴展的具體運用,為設計高效、穩(wěn)定的數(shù)據(jù)庫管理系統(tǒng)提供寶貴資源。
關(guān)鍵詞:通用模塊;添加;刪除;編輯
中圖分類號:TP311 文獻標識碼:A 文章編號:1009-3044(2016)25-0011-05
Abstract: Using the built module database project of VB.NET technology and listView control,that demonstrate the application of method of general module data,Also described the specific use of inheritance and expansion of class. These Provide valuable resources for the database management system design of high efficiency and stable.
Key words: universal module; add; delete; edit
1 引言
VB.NET繼承類允許擴展類,可以創(chuàng)造一個帶有一定功能的新類。如果有部分功能已經(jīng)能由一個已經(jīng)存在的類提供了,則可以擴展原來的那個類來構(gòu)建一個新類。那么新建的這個類成為子類或者繼承類,而原來的那個類稱為父類或者基類。擴充類的過程稱為擴展,關(guān)鍵字為inherit 用于描述擴展類的行為。在VB.NET中一個類只能有一個父類。
2 數(shù)據(jù)庫通用模塊代碼及其說明
打開Visual Studio 2010,新建一個工程,名稱假設為SalesManager,在項目下新建一個文件夾,命名為TYConfig.在該文件夾下,添加6個類。其中TYConnection為父類,TYCommand、TYDataReader、TYDataTable子類3個為子類或稱繼承類。如圖1解決方案資源資源管理器所示。下面分別介紹主要代碼(注:單引號“‘”后面的文字為簡要說明,與代碼同行的是說明同行的代碼;單獨行的是說明下一行的代碼)。
2.1 數(shù)據(jù)庫連接通用模塊
父類TYConnection
Imports System.Data.SqlClient ‘連接SQL Server
Namespace TYConfig ‘命名空間名稱為TYConfig
Public Class TYConnection ‘聲明類TYConnection
‘聲明一個受保護變量存儲連接數(shù)據(jù)庫的信息
Protected ConnStr As String
‘聲明用于數(shù)據(jù)庫連接的保護成員
Protected conn As SqlConnection
Protected Sub Open()
‘判斷連接字符串是否為空
If ConnStr Is Nothing Or ConnStr = "" Then
MessageBox.Show("請指定連接字符串!")
Return
End If
‘實例化Connection類
conn = New SqlConnection(ConnStr)
conn.Open() ‘打開數(shù)據(jù)庫
End Sub
Protected Sub Close()
conn.Close() ‘關(guān)閉連接
End Sub
End Class
End Namespace
在這“TYConnection”類中,最上面二句和最下面一句,表示命名空間的定義,在下面3個繼承類中不再重復。
2.2 創(chuàng)建TYCommand 類
該類包括 Function過程,分別實現(xiàn)添加、刪除、更新數(shù)據(jù)。
Imports System.Data.SqlClient ‘連接SQL Server
Namespace TYConfig ‘命名空間名稱為TYConfig
Public Class TYCommand ‘TYCommand類的聲明
Inherits TYConnection ‘為繼承TYConnection類的功能,重用這個類里的功能,避免代碼重復
Public Sub New(ByVal str As String) ‘創(chuàng)建有一個參數(shù)為str的構(gòu)造函數(shù),指定連接信息字符串
ConnStr = str
End Sub
Public Function Insert(ByVal strSQL As Strin ) As Integer ‘添加數(shù)據(jù)的Function過程
Open() ‘連接數(shù)據(jù)庫
‘創(chuàng)建 SqlCommand 實例
Dim cmd as SqlCommand=New SqlCommand(strSQL,comm)
‘count 表示受影響的行數(shù),初始化為0
Dim count As Integer=0
Count=cmd.ExecuteNonQuery()
Close() ‘關(guān)閉數(shù)據(jù)庫
End Fuction
‘刪除數(shù)據(jù)的Function過程 ,有三個參數(shù),分別對應數(shù)據(jù)庫中的表名、需要刪除的條件
Public Function Delete(ByVal table As String, ByVal row As String, ByVal value As String) As Integer
Open() ‘連接數(shù)據(jù)庫
‘創(chuàng)建SQL命令
Dim strSQL As String = "Delete From " + table + " Where " + row + "=" + value
‘創(chuàng)建 SqlCommand 實例
Dim cmd As SqlCommand =New SqlCommand(strSQL, conn)
‘count 表示受影響的行數(shù),初始化為0
Dim count As Integer = 0
count = cmd.ExecuteNonQuery()
Close() ‘關(guān)閉數(shù)據(jù)庫
Return count
End Function
‘更新數(shù)據(jù)的Function過程
Public Function Update(ByVal table As _
String, ByVal strContent As String, _
ByVal row As String, ByVal value As String) As Integer
Open() ‘連接數(shù)據(jù)庫
Dim strSQL As String = "Update " + table + " Set " + strContent + " Where " + row + "=" + value
Dim cmd As SqlCommand = New SqlCommand(strSQL, conn)
Dim count As Integer = 0
count = cmd.ExecuteNonQuery()
Close() ‘關(guān)閉數(shù)據(jù)庫
Return count
End Function
End Class
End Namespace
2.3 創(chuàng)建DataBinding 類
用于ListView控件與數(shù)據(jù)庫綁定。如果與ComboBox、TextVox、ListBox等控件綁定,方法類似。這里以ListView控件為例。
Namespace TYConfig ‘命名空間名稱為TYConfig
Public Class DataBinding
‘根據(jù)指定表和指定查詢條件,填充ListView.分別有控件類型、表名、列數(shù)、查詢條件
Public Shared Sub FillListView(ByRef lsv As ListView, ByVal tableName As String, ByVal num As Integer, _ ByVal connStr As String, Optional ByVal field As String = "",
Optional ByVal op As String = "=", Optional ByVal value As String = "")
‘清空ListView
lsv.Items.Clear()
‘設置SQL 語句,即讀出表
Dim SQLString As String = "SELECT * FROM " & tableName
‘如果有查詢條件,則將查詢條件追加到SQL語句
If field <> "" Then
SQLString += " Where " & field & op & value
End If
‘創(chuàng)建DBDataTable對象
Dim dt As TYDataTable = New TYDataTable(connStr)
‘調(diào)用DBDataTable 的CreateDataTable函數(shù),得到DataTable表
Dim table As DataTable = dt.CreateDataTable(SQLString, tableName)
‘在循環(huán)中遍歷DataTable表,逐行逐列把表中的內(nèi)容加入到ListView控件中
Dim UserRow As DataRow
Dim LItem As ListViewItem
For Each UserRow In table.Rows
LItem = New ListViewItem(UserRow(0). ToString.Trim())
Dim i As Integer
For i = 1 To num - 1
LItem.SubItems.Add(UserRow(i). ToString().Trim())
Next
lsv.Items.Add(LItem)
Next
End Sub
End Class
2.4創(chuàng)建TYDataReader類
Imports System.Data.SqlClient ‘連接SQL Server
Namespace TYConfig ‘命名空間名稱為TYConfig
Public Class TYDataReader
Inherits TYConnection
‘在構(gòu)造函數(shù)中指定連接信息字符串
Public Sub New(ByVal str As String)
ConnStr = str
End Sub
Public Function CreateDataReader( ByVal strSQL As String,ByVal table As String) As SqlDataReader
‘打開數(shù)據(jù)庫連接
Open()
‘創(chuàng)建SqlCommand對象
Dim cmd As SqlCommand =New SqlCommand(strSQL, conn)
‘ExecuteReader執(zhí)行SQL語句并返回SqlDataReader
Dim dr As SqlDataReader = cmd.ExecuteReader()
‘返回DataReader
Return dr
End Function
End Class
End Namespace
2.5創(chuàng)建TYDataTable類
Imports System.Data.SqlClient ‘連接SQL Server
Namespace TYConfig ‘命名空間名稱為TYConfig
Public Class TYDataTable
Inherits TYConnection
‘在構(gòu)造函數(shù)中指定連接信息字符串
Public Sub New(ByVal str As String)
ConnStr = str
End Sub
Public Function CreateDataTable( ByVal strSQL As String, ByVal table As String) As DataTable
Open() ‘連接數(shù)據(jù)庫
‘使用連接字符串和SqlConnecton創(chuàng)建 SqlDataAdapter的實例
Dim da As SqlDataAdapter = New SqlDataAdapter(strSQL, conn)
Dim ds As New Data.DataSet() ‘創(chuàng)建DataSet對象
da.Fill(ds) ‘填充DataSet
Close() ‘關(guān)閉數(shù)據(jù)庫
Return ds.Tables(0) ‘返回DataTable
End Function
End Class
End Namespace
3 數(shù)據(jù)庫公用模塊運用準備
有了以上5個通用模塊,配合ListView控件,便可以方便設計一個簡單的數(shù)據(jù)庫管理系統(tǒng),能實現(xiàn)對數(shù)據(jù)的添加、編輯、刪除、刷新等基本操作。
3.1數(shù)據(jù)庫準備
本文以SQL Server2008為例,假設在C盤根目錄下有一個銷售統(tǒng)計的數(shù)據(jù)庫,文件名為Sales.mdf。其中一個通訊錄表名為txl。數(shù)據(jù)和結(jié)構(gòu)如圖2所示:
(必須注意:如果表中有自動增量必須取消,否則添加或修改數(shù)據(jù)時會出錯。)
3.2 操作界面設計
6個文本框和標簽框,4個命令按鈕,1個ListView控件(ListView必須設置好如下屬性:View為Details;GridLines為True;Column的ColumnHeader集合編輯器里要加上六列,并將text改為真實列名;滾動條設置為可用)。界面如圖3所示:
4 數(shù)據(jù)庫通用模塊的運用說明
在TYConfig文件夾下再創(chuàng)建ConncetionString類,用于連接數(shù)據(jù)庫
Namespace TYConfig
Public Class ConnectionString
Public ConnectionInfo As String = "數(shù)據(jù)庫連接字符串"
End Class
End Namespace
注:數(shù)據(jù)庫連接字符串:VS2010數(shù)據(jù)菜單——添加數(shù)據(jù)源(若已添加,則按顯示數(shù)據(jù)源)——數(shù)據(jù)源配置向?qū)Вx“數(shù)據(jù)庫”——“下一步”,選“數(shù)據(jù)集”——計算機名稱.數(shù)據(jù)庫名稱.dbo
假設計算機屬性名稱為PCName,數(shù)據(jù)庫名稱為sales,則在文本框里自動出現(xiàn): PCName.sales.dbo
也可以做其他選擇。此時,將下面“連接字符串”左側(cè)的“+”號點開,就看到字符串為:
Data Source=PCName;Initial Catalog=sales; User ID=sa
下一步,“是否將連接保存為”: salesConnectionString
下一步,“正在檢索數(shù)據(jù)庫信息”,選擇表、視圖、存儲過程、函數(shù)等復選框。DataSet名稱為:salesDataSet
此時便實現(xiàn)VS與SQL數(shù)據(jù)庫的連接。
回到操作界面,給每個命令按鈕添加代碼
在Form Class類里,最前面需要輸入Imports SalesManager.TYConfig(不需要TYConfig的命名空間語句)
4.1“添加”按鈕的click事件代碼
‘注意數(shù)據(jù)類型,第一列為int,所以不用單引號
‘利用SQL插放語句,將各文本框里的數(shù)據(jù),定義到txl表
Dim SQLstr As String = "Insert into txl values(" & TextBox1.Text & "," & TextBox2.Text & ", " & TextBox3.Text & " , " & TextBox4.Text & " , " & TextBox5.Text & ", " & TextBox6.Text & ")"
Dim cmd As TYCommand = New TYCommand (New ConnectionString().ConnectionInfo)
If cmd.Insert(SQLstr) > 0 Then
MsgBox("信息添加成功!", MsgBoxStyle.DefaultButton1, "添加信息")
Else
MsgBox("添加信息失敗!")
End If
TextBox1.Text ="": TextBox2.Text="": TextBox3.Text = "": TextBox4.Text = "" : TextBox5.Text = "" : TextBox6.Text = ""
DataBinding.FillListView(ListView1, "txl", 6, New ConnectionString().ConnectionInfo)
End Sub
4.2 “刪除”按鈕click事件代碼
If ListView1.SelectedItems.Count = 0 Then
MsgBox("請選擇需要刪除的行")
Exit Sub
End If
Dim cmd As TYCommand = New TYCommand( New ConnectionString().ConnectionInfo)
‘利用TYCommand中的Delect Function過程,判定刪除是否成功
If cmd.Delete("txl", "tID”, ListView1.SelectedItems(0).Text) > 0 Then
MsgBox("刪除數(shù)據(jù)成功!", MsgBoxStyle.OkOnly, "刪除")
Else
MsgBox("刪除失??!")
End If
‘刪除符合條件的行號后重新將表中數(shù)據(jù)綁定到ListView1控件中
DataBinding.FillListView(ListView1, "txl", 6, New ConnectionString().ConnectionInfo)
4.3 “更新”按鈕click事件代碼
Dim cmd As TYCommand = New TYCommand( New ConnectionString().ConnectionInfo)
Dim strContent As String = "tID= " & TextBox1.Text & ", _
tName=" & TextBox2.Text & ", tEmail=" & TextBox3.Text & " , tMobile=" & TextBox4.Text & ", _
tHomePhone=" & TextBox5.Text & ", tMemo=" & TextBox6.Text & ""
‘利用TYCommand中的Update Function過程,判斷更新是否成功
If cmd.Update("txl", strContent, "tid", "" & TextBox1.Text & "") > 0 Then
MsgBox("修改信息成功!", MsgBoxStyle.OkOnly, "修改信息")
Else
MsgBox("修改信息未被接受,請檢查你所做的修改是否正確。", MsgBoxStyle.Critical, "修改信息")
End If
DataBinding.FillListView(ListView1, "txl", 6, New ConnectionString().ConnectionInfo)
4.4“顯示ListVew1數(shù)據(jù)”按鈕的click事件代碼
DataBinding.FillListView(ListView1, "txl",6, New ConnectionString().ConnectionInfo)
4.5 ListView1_Click事件代碼
‘先清空文本框數(shù)據(jù)
TextBox1.Text = "":TextBox2.Text = "":TextBox3.Text = "":
TextBox4.Text = "":TextBox5.Text = "":TextBox6.Text = "":
If ListView1.SelectedItems.Count = 0 Then Exit Sub
‘當鼠標選中ListView1控件中某一行時,自動將該行中的每一個數(shù)據(jù),賦值給各文本框
TextBox1.Text =ListView1._
SelectedItems(0). SubItems(0).Text
TextBox2.Text = ListView1. SelectedItems(0).SubItems(1).Text
TextBox3.Text = ListView1.SelectedItems(0).SubItems(2).Text
TextBox4.Text = ListView1. SelectedItems(0).SubItems(3).Text
TextBox4.Text = ListView1. SelectedItems(0).SubItems(4).Text
TextBox6.Text = ListView1.SelectedItems(0).SubItems(5).Text
4.6 補充說明
該程序調(diào)試時,如果出現(xiàn)如圖4所示的異常情況,則說明需要添加引用,最簡單的解決方法就是 導入“System.Windows.Forms”,即在該類代碼的第一行,添加:Imports System.Windows.Forms,即可解決。
另外,可以在操作界面上加上菜單或右鍵快捷菜單以及多個表單頁面,并且通過總界面作為父窗口,將所有界面貫穿起來,那么無論多么復雜的數(shù)據(jù)庫,都能輕松構(gòu)建。
5 結(jié)束語
由于VB.net技術(shù)可以創(chuàng)建數(shù)據(jù)庫通用性模塊,這些模塊適用于任何一個關(guān)系數(shù)據(jù)庫系統(tǒng)的設計,當理解掌握并熟練應用后就能提高數(shù)據(jù)庫設計效率,也使軟件設計變得相當簡單,使非計算機專業(yè)的普通電腦愛好者也能涉足其中,感受無窮樂趣。
參考文獻:
[1] 石志國,劉冀偉.張維存.VB.NET數(shù)據(jù)庫編程[M].北京:清華大學出版社,2009.
[2] 青島樂合信息技術(shù)有限公司.青島海爾軟件有限公司. VB.NET程序設計[M].北京:電子工業(yè)出版社,2011.
[3] 余青松,江紅.VB.NET 程序設計[M].北京:清華大學出版社,2011.
[4] http://blog.csdn.net/xiao714041/article/details/45217969[EB/OL].