我的代码无法连接到Microsoft SQL Server 2008中的数据库。它尝试但出现错误时出现以下错误:"运行时错误SQL Server不存在或访问被拒绝。服务器受密码保护,但我认为我考虑到了这一点。任何帮助,将不胜感激!发生错误的地方是粗体
Public Sub dataextract()
'Create a connection object.'
Dim cndatabase_name As ADODB.Connection
Set cndatabase_name = New ADODB.Connection
'Provide the connection string.'
Dim strConn As String
'Use the SQL Server OLE DB Provider.'
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the database on the server.'
strConn = strConn & "DATA SOURCE=Server_name;INITIAL CATALOG=database_name;"
' Login details.'
strConn = strConn & " UID=username; PWD=password"
'Now open the connection.'
'ERROR HERE:'
cndatabase_name.Open strConn***
' Create a recordset object.'
Dim rsdatabase_name As ADODB.Recordset
Set rsdatabase_name = New ADODB.Recordset
With rsdatabase_name
' Assign the Connection object.'
.ActiveConnection = cndatabase_name
' Extract the required records.'
.Open "SELECT * FROM table_name"
' Copy the records into cell A1 on Sheet1.'
Sheet1.Range("A1").CopyFromRecordset rsdatabase_name
' Tidy up'
.Close
End With
cndatabase_name
Set rsdatabase_name = Nothing
Set cndatabase_name = Nothing
End Sub
答案 0 :(得分:0)
尝试更改
' Create a recordset object.'
Dim rsdatabase_name As ADODB.Recordset
Set rsdatabase_name = New ADODB.Recordset
With rsdatabase_name
' Assign the Connection object.'
.ActiveConnection = cndatabase_name
' Extract the required records.'
.Open "SELECT * FROM table_name"
' Copy the records into cell A1 on Sheet1.'
Sheet1.Range("A1").CopyFromRecordset rsdatabase_name
' Tidy up'
.Close
End With
cndatabase_name
Set rsdatabase_name = Nothing
Set cndatabase_name = Nothing
到
' Create a recordset object.'
Dim rsdatabase_name As ADODB.Recordset
Set rsdatabase_name = New ADODB.Recordset
With rsdatabase_name
' Assign the Connection object.'
.ActiveConnection = cndatabase_name
' Extract the required records.'
.Open "SELECT * FROM table_name"
' Tidy up'
.Close
End With
Sheet1.Range("A1").CopyFromRecordset rsdatabase_name
Set rsdatabase_name = Nothing
Set cndatabase_name = Nothing
你有一个随机的" cndatabase_name"坐在你的代码中。
:)