我有以下代码,我试图用来从sql中恢复数据。连接很好,一切正常,但是,我想将下面代码的内容存储在访问表中。 请有人帮忙吗?
Public PERSONALDBCONT As Object, _
SQLSTR As String, SQLSTR1 As String, _
SQLSTR2 As String, SQLSTR3 As String, _
RecCount As String, DB As String
Function CONNECT_TO_DB()
Set PERSONALDBCONT = CreateObject("ADODB.connection")
Dim SCONN As String
SCONN = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & tempdb & ";Data Source=WBACUKSQLPD001;" & _
"Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=WBAC173427;Use Encryption for Data=False;Tag with column collation when possible=False"
PERSONALDBCONT.Open SCONN
End Function
Function CLOSE_CONNECTION_TO_SQL()
On Error Resume Next
PERSONALDBCONT.Close
Set PERSONALDBCONT = Nothing
On Error GoTo 0
End Function
Sub SQL_()
Dim rs As Object
Dim iCols As Integer
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ERR
CONNECT_TO_DB
Dim SQLSTR As String
SQLSTR = "Select top 1 * from sys.objects"
rs.Open SQLSTR, PERSONALDBCONT
Exit Sub
ERR:
CLOSE_CONNECTION_TO_SQL
MsgBox "There was an error at " & Stage & "." & vbNewLine & "Please see the instructions and investigate"
If Application.Visible = False Then Application.Visible = True
End
End Sub
答案 0 :(得分:0)
对于不与完整表交互的特定查询,请考虑事先构建可以容纳来自SQL Server查询的数据的Access表。然后,使用迭代追加查询或记录集更新将SQL Server记录集迁移到Access表:
附加查询 (使用参数化querydef)
' ... same code as above ... '
Dim db As Database
Dim qdef As Querydef
Dim strSQL As String
Set db = CurrentDb
' PREPARE SQL STATEMENT (SPECIFY PARAM NAMES AND TYPES IN FIRST LINE) '
strSQL = "PARAMETERS Col1 Text(100), Col2 Text(100), Col3 Integer, Col4 Boolean;" _
& " INSERT INTO AccessDestinationTable (Col1, Col2, Col3)" _
& " VALUES ([Col1], [Col2], [Col3]);"
' LOOP THROUGH SQL SERVER RS '
Do While Not SqlServerRS.EOF
Set qdef = db.CreateQueryDef("", strSQL)
qdef!Col1 = SqlServerRS!Col1
qdef!Col2 = SqlServerRS!Col2
qdef!Col3 = SqlServerRS!Col3
qdef.Execute
SqlServerRS.MoveNext
Loop
SqlServerRS.Close
Set qdef = Nothing
Set db = NOthing
记录集更新 (使用两个开放记录集)
' ... same code as above ... '
Dim db As Database
Dim AccessRS As Recordset
Set db = CurrentDb
Set AccessRS = db.OpenRecordset("AccessDestinationTable")
' LOOP THROUGH SQL SERVER RS '
Do While Not SqlServerRS.EOF
' OPEN EDIT MODE OF ACCESS RECORSET, SET VALUES TO FIELDS, APPEND ROW '
With AccessRS
.Edit
!Col1 = SqlServerRS!Col1
!Col2 = SqlServerRS!Col2
!Col3 = SqlServerRS!Col3
.Update
End With
SqlServerRS.MoveNext
Loop
AccessRS.Close
SqlServerRS.Close