當前位置:成語大全網 - 新華字典 - 在VS.net中怎樣連接壹個數據庫,並將他的內容顯示出來

在VS.net中怎樣連接壹個數據庫,並將他的內容顯示出來

妳有數據庫嗎?

連接妳的數據庫的位置,加他的 連接條件就可以拉下面是壹個連接數據庫的模塊,大家可以使用它來連接SQL數據庫,使用起來比ADO控件還簡單:

代碼如下:

Public rsNew As ADODB.Recordset

Public CnNew As ADODB.Connection

Public addFlag As Boolean

'連接數據庫

Public Function OpenCn() As Boolean

Dim Mag As String

On Error GoTo strErrMag

Set CnNew = New ADODB.Connection

CnNew.ConnectionTimeout = 25

CnNew.Provider = "sqloledb"

CnNew.Properties("data source").value = "" 'SQL服務器的名

CnNew.Properties("initial catalog").value = "pubs"'庫名

CnNew.Properties("integrated security").value = "SSPI"'登陸類型

'con.Properties("user id").value = "sa"

'con.Properties("password").value = "wwww"

CnNew.Open

OpenCn = True

addFlag = True

Exit Function

strErrMag:

Mag = "數據庫末連接"

Call MsgBox(Mag, vbOKCancel, "錯誤:數據庫連接")

addFlag = False

End

End Function

Public Sub Clocn()

'閉關數據庫

On Error Resume Next

If CnNew.State <> adStateClosed Then CnNew.Close

Set CnNew = Nothing

End Sub

Public Function OpenRs(ByVal strSql As String) As Boolean

'連接數據庫記錄集

Dim Mag As String

Dim rpy As Boolean

On Error GoTo strErrMag

Set rsNew = New ADODB.Recordset

If addFlag = False Then rpy = OpenCn

With rsNew

.ActiveConnection = CnNew

.CursorLocation = adUseClient

.CursorType = adOpenKeyset

.LockType = adLockOptimistic

.Open strSql

End With

addFlag = True

OpenRs = True

Exit Function

strErrMag:

Mag = "數據庫數據集末連接"

Call MsgBox(Mag, vbOKOnly, "錯誤:數據庫連接")

OpenRs = False

End

End Function

Public Sub cloRs()

'閉關數據集

On Error Resume Next

If rsNew.State <> adStateClosed Then rsNew.Close

Set rsNew = Nothing

End Sub