搞過資料庫開發的都知道,開發資料庫系統,首先在有一個很好的設計,才使我們的工作順利進行,在概要設計時,我們要訪問資料庫,顯然開發一個訪問資料的類是我們代碼可重要的實現基礎,那麼,我們如何來開發這麼一個類呢?下面的代碼就是一個皺形,可以說不是很成熟,但是它在我搞資料庫開發過程中起了很大的作用。
筆者是第一次開始資料庫系統,在分析和設計上欠經驗,以下的類可以不適合您的需求,無所謂,類是對我們訪問資料的一個封裝,是代碼可重用的一個體現,相信你在看完My Code後,會有寫一個更強大功能的類來縱你的資料,好!我很樂意向你學習,如果你寫到一個功能強大的類,請不要忘了和我一起分享你的快樂!也讓我領略一下你的代碼!呵呵^_^
Imports System.Data
Imports System.Data.SqlClient
Public Class SQLDB
Private ServerName As String
Private DatabaseName As String
Private UserName As String
Private UserPassword As String
Private cnn As SqlConnection
'建構函式
Public Sub New()
MyBase.new()
ServerName = "localhost"
UserName = "sa"
UserPassword = "sa"
End Sub
Public Sub New(ByVal server As String, ByVal database As String, ByVal uid As String, ByVal pwd As String)
ServerName = server
DatabaseName = database
UserName = uid
UserPassword = pwd
End Sub
Public Function open(ByRef msg As String) As Boolean
cnn = New SqlConnection
Dim cnnstr As String = "data source=" + ServerName + "; initial catalog=" + DatabaseName + "; user id=" + UserName + "; pwd=" + UserPassword
cnn.ConnectionString = cnnstr
Try
cnn.Open()
Catch ex As Exception
msg = ex.Message
Return False
End Try
Return True
End Function
Public Function SelectDB(ByVal sql As String, ByRef msg As String) As DataSet
Dim ds As DataSet
ds = New DataSet
Try
If cnn.State = ConnectionState.Closed Then
cnn.Open()
End If
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, cnn)
da.Fill(ds)
cnn.Close()
Catch ex As Exception
msg = ex.Message
ds = Nothing
Return ds
End Try
Return ds
End Function
Public Function UpadateDB(ByVal sql As String, ByRef msg As String) As Boolean
Dim cma As SqlCommand = New SqlCommand
Try
If cnn.State = ConnectionState.Closed Then
cnn.Open()
End If
cma.Connection = cnn
cma.CommandText = sql
cma.CommandType = CommandType.Text
cma.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
msg = ex.Message
Return False
End Try
Return True
End Function
End Class
在設計此類時只考慮自己的使用方式,因為我對預存程序不太瞭解,也沒有怎麼寫過,更談不上使用了!但是爭取在下次開發資料庫時候一定用上,到時我再完善該類,為自己使用ADO.NET提供方便!