VB连接Sql Server 2000

2024年11月15日 02:07
有3个网友回答
网友(1):

这是最简单直接的方法:
Private Sub Command1_Click()
Adodc1.ConnectionString = "UID=ss;PWD=ss;Driver={SQL Server};Server=SQL服务器名称;Database=BookStoreManagement;dsn= ,,Connection=adConnectAsync"
Adodc1.LockType = adLockReadOnly
Adodc1.CommandType = adCmdText
Adodc1.ConnectionTimeout = 15
Adodc1.RecordSource = "select * from [库存]"
Set DataGrid1.DataSource = Adodc1
End Sub

这个方法需简单,但不灵活而且耗资源,建议还是用ADODB,可编程性高。

================================================
简单的说,ADODC是ADO控件,ADODB是ADO对象(ActiveX Data Objects),只要在工程中引用 Microsoft ActiveX Data Objects 就可以了,ADODB全部用代码方式连接数据库,不用画(ADODC)控件,功能灵活性比ADODC控件强得多。

=================================================
ADODB 连接SQL Server 2000 方法:

先在工程中引用 Microsoft ActiveX Data Objects 2.x

连接代码:

Private mCnn As ADODB.Connection
Private mRst As ADODB.Recordset

Private Sub Form_Load()
On Error GoTo ErrorLoad
Dim strCnn As String

Command1.Caption = "查询SQL数据"

strCnn = "UID=ss;PWD=ss;Driver={SQL Server};Server=SQL服务器名称;Database=BookStoreManagement;dsn= ,,Connection=adConnectAsync"
Set mCnn = New ADODB.Connection
mCnn.CursorLocation = adUseClient
mCnn.ConnectionString = strCnn
mCnn.Open '打开数据源

Exit Sub
ErrorLoad:
MsgBox "错误编号:" & Err.Number & vbCrLf & "错误信息:" & Err.Description, vbCritical, "连接错误"
mCnn.ConnectionString = ""
Command1.Enabled = False
End Sub

Private Sub Command1_Click()
On Error GoTo ErrorLoad
Dim mStr As String

If mRst.State = adStateOpen Then mRst.Close: Set mRst = Nothing

mStr = "select * from 库存"
Set mRst = New ADODB.Recordset
mRst.Open mStr, mCnn, adOpenKeyset, adLockReadOnly
Set DataGrid1.DataSource = mRst

Exit Sub
ErrorLoad:
MsgBox "错误编号:" & Err.Number & vbCrLf & "错误信息:" & Err.Description, vbCritical, "连接错误"
End Sub

Private Sub Form_Unload(Cancel As Integer)
If Not (mRst Is Nothing) Then
If mRst.State = adStateOpen Then mRst.Close: Set mRst = Nothing
End If
If Not (mCnn Is Nothing) Then
If mCnn.State = adStateOpen Then mCnn.Close: Set mCnn = Nothing
End If
End Sub

网友(2):

配置ODBC是在和“控制面板”里选择“数据源 (ODBC)”
在里面选择“系统DSN”,可以在里面添加你想要的数据源

网友(3):

不懂