|
楼主 |
发表于 2023-7-2 19:53
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
最近在用VBA写程序,之前都是用MDB数据库做测试,想转到SQL数据库,发现一个问题,就是代码不变,我只是把MDB数据库的ODBC连接换成SQL,读取一次速度就慢了7秒左右(5万条记录左右,MDB方式要1.3秒左右,SQL方式要8.5秒左右)。太离谱了。请问您知道原因吗?有改进的余地吗?这种情况不应该啊,SQL数据库应该比MDB数据库更快才对。
大概代码如下:
- Sub ceshi()
- #If ProjectStatus = "DEV" Then
- Dim cn As ADODB.Connection
- Dim rs As ADODB.Recordset
- Set cn = New ADODB.Connection
- Set rs = New ADODB.Recordset
- #Else
- Dim cn As Object
- Dim rs As Object
- Set cn = CreateObject("ADODB.Connection")
- Set rs = CreateObject("ADODB.Recordset")
- #End If
-
- Dim lianjie As String, shijian As Double, dayArr() As Variant
- lianjie = .Cells(1, 1).Value 'MDB数据库和SQL数据库的选择
- shijian = Timer()
- With cn
- If lianjie = "本地" Then
- Sql = "select * from ceshi where dt<#" & Now() & "#"
- .Provider = "Microsoft.ACE.oledb.12.0"
- .ConnectionString = "data source=" & ActiveWorkbook.Path & "\test.mdb"
- Else
- Sql = "select * from ceshi where dt<'" & Now() & "'"
-
- .Provider = "sqloledb"
- .ConnectionString = "Server=.;Database=test;Uid=sa;Pwd=sa;"
- End If
- .Open
- End With
- rs.Open Sql, cn, 1, 1
- hangCount = rs.RecordCount
- If hangCount > 0 Then
- dayArr = rs.GetRows
- Debug.Print Format(Timer - shijian, "0.0") '就载入记录集就 差了7秒左右。
- '.........
-
- End If
-
- Erase dayArr
- rs.Close
- Set rs = Nothing
- cn.Close
- Set cn = Nothing
- End Sub
复制代码 |
|