|
楼主 |
发表于 2008-11-9 11:31:46
|
显示全部楼层
2008-11-9 今天主要学习将数据库、数据库中的数据表以及数据表中的所有记录返回在excel中。
Sub 返回SqlServer中所有数据库的名称()
Dim Cn As ADODB.Connection, rs As ADODB.Recordset
Dim Db As String, MyTable As String, CnStr As String, SqlStr As String
Dim Ws As Worksheet, Rng As Range
Set Cn = New ADODB.Connection
Db = "Master"
Set Ws = Sheet5
With Ws
.[a2:a65536].ClearContents
Set Rng = .Range("a1")
End With
CnStr = "provider=sqloledb;server=renh;user id=sa;pwd=;database=" & Db
Cn.Open CnStr
'创建数据库名称查询记录集
'查看Sql Server联机帮助sysdatabases
'最初安装 SQL Server 时,sysdatabases 包含 master、model、msdb、mssqlweb 和 tempdb 数据库的项。该表只存储在 master 数据库中。
SqlStr = "select name from sysdatabases "
Set rs = Cn.Execute(SqlStr)
i = 0
Do While Not rs.EOF
i = i + 1
Rng.Offset(i, 0) = rs.Fields("name")
rs.MoveNext
Loop
MsgBox "Sql Server数据库中" & Db & "中共有:" & i - 1 & "个数据库!"
Cn.Close
Set Cn = Nothing
Set rs = Nothing
End Sub
Sub 返回数据库中所有数据表()
Dim Cn As ADODB.Connection, rs As ADODB.Recordset
Dim Db As String, MyTable As String, CnStr As String, SqlStr As String
Dim Ws As Worksheet, Rng As Range
Set Cn = New ADODB.Connection
Set Ws = Sheet5
With Ws
Db = .Range("c1")
MyTable = .Range("d2")
.[b3:b65536].ClearContents
Set Rng = .Range("b1")
End With
CnStr = "provider=sqloledb;server=renh;user id=sa;pwd=;database=" & Db
Cn.Open CnStr
'利用sql语句创建一个数据表记录集
SqlStr = "select name from sysobjects where xtype='u'"
'sysobjects表记录了所有对象,包括“表”, “存储过程”,“触发器”,等等。
Set rs = Cn.Execute(SqlStr)
i = 1
Do While Not rs.EOF
i = i + 1
Rng.Offset(i, 0) = rs.Fields("name")
rs.MoveNext
Loop
MsgBox "数据库" & Db & "中共有:" & i - 1 & "个用户表!"
Cn.Close
Set Cn = Nothing
Set rs = Nothing
End Sub
Sub 导出数据表中所有记录()
'导出数据表中所有记录
Dim Cn As ADODB.Connection, rs As ADODB.Recordset
Dim Db As String, MyTable As String, CnStr As String, SqlStr As String
Dim Ws As Worksheet, Rng As Range
Set Cn = New ADODB.Connection
Set Ws = Sheet5
With Ws
Db = .Range("c1")
MyTable = .Range("d2")
.[c4:iv65536].ClearContents
Set Rng = .Range("c4")
End With
CnStr = "provider=sqloledb;server=renh;user id=sa;pwd=;database=" & Db
Cn.Open CnStr
If Cn.State = adStateOpen Then
'MsgBox "数据库连接成功!"
SqlStr = "select * from " & MyTable
Set rs = Cn.Execute(SqlStr)
'将字段名称返回在工作表中,Rs.Fields.Count返回记录集字段的个数
For i = 1 To rs.Fields.Count
'Fields集合的序号,即Fields(n) n是一个记录中字段从左到右排列的序号,第一个字段的序号为0,所以这里使用i-1
Rng.Offset(0, i - 1) = rs.Fields(i - 1).Name
Next i
Rng.Offset(1, 0).CopyFromRecordset rs
End If
Cn.Close
Set Cn = Nothing
End Sub
请查看附件,在安装sql server后,修改服务器名称和数据库名称,当然也可以连接公司的数据库,返回公司所有数据库名称以及对应的数据表和数据表记录。
[ 本帖最后由 hner 于 2008-11-9 11:34 编辑 ] |
|