VBA中用ADO连接SqlServer2005

按Alt+F11打开代码窗口,点击菜单上的"工具">>"引用",勾选它:Microsoft ActiveX Data Objects 2.x

'================================
    '   连接SqlServer2005

'================================

 

Private Sub ConnectDB()

 

Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset

Dim strCnn As String
   
Dim strHost As String
Dim strDatabaseName As String
Dim strUserName As String
Dim strPassword As String
Dim strSQL As String


Dim lCountOfFields As Long
Dim lrow As Long
Dim lcol As Long

 

'================================
    '   定义连接字符串
'================================

 

strHost = "10.203.0.XX"       'Sqlsever服务器IP地址或计算机名
strDatabaseName = "master"    '连接数据库名
strUserName = "sa"            '登录用户名

strPassword = "123"           '登录密码

 

On Error GoTo ConnectErr:

 

'================================
    '   建立连接
'================================

 

    strCnn = ""
    strCnn = strCnn & "Provider=SQLOLEDB;"
    strCnn = strCnn & "Password=" & strPassword & ";"
    strCnn = strCnn & "User ID=" & strUserName & ";"
    strCnn = strCnn & "Initial Catalog=" & strDatabaseName & ";"
    strCnn = strCnn & "Data Source = " & strHost

 

    Set cnn= New ADODB.Connection

    With cnn

        .ConnectionString = strCnn
        .Open
    End With
   
    MsgBox "Connect successfully!", vbOKOnly + vbInformation

 

'================================
    '   查询数据集
'================================

 

Set rs = New ADODB.Recordset
strSQL = "select * from spt_values "

rs.Open strSQL, cnn, adOpenForwardOnly, adLockReadOnly

  

'================================
    '   将数据集填充到sheet
'================================

  
    lrow = 2
    lcol = 2

    
    With Worksheets("Sheet1")
        lCountOfFields = rs.Fields.Count
        .Range(Cells(lrow, lcol).Address & ":" & Cells(lrow + 2, lcol + lCountOfFields - 1).Address).ClearContents
        .Cells(lrow, lcol).CopyFromRecordset rs
    End With
   
    rs.Close
   
    Exit Sub
    
ConnectErr:
    MsgBox "Connect error!", vbOKOnly + vbCritical


End Sub

 

----------------------------------------------------------------------------------

 

 

'================================
    '   断开连接

'================================

 

Public Sub CloseConnect()

 

 

On Error GoTo DisconnectErr:
    cnn.Close
    Set cnn = Nothing
    MsgBox "Disconnect successfully!", vbOKOnly + vbInformation
    Exit Sub
   
DisconnectErr:
    MsgBox "Disconnect error!", vbOKOnly + vbCritical


End Sub

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值