如何在Microsoft Access 2010中设置与SQL Server 2008的ADODB连接?

时间:2014-06-21 21:10:13

标签: sql-server-2008 vba adodb

我刚在笔记本电脑上安装了SQL Server 2008。我也安装了Microsoft Access 2010。使用VBA,我试图在SQL Server上创建一个到我自己的数据库的ADODB连接,但是我找不到正确的代码行:

当我在下面使用它时,它不起作用。 我的电脑名称是LAPTOPX,数据库是HomeSQL。

我确信这很容易但是因为我刚刚开始,我似乎无法找到正确的方式来提问。

谢谢!

Dim DBCONT As Object

Set DBCONT = CreateObject("ADODB.Connection")
Dim strDbPath As String
strDbPath = "LAPTOPX/HomeSQL"
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                        "Data Source =" & strDbPath & ";" & _
                        "Jet OLEDB:Engine Type=5;" & _
                        "Persist Security Info=False;"
DBCONT.Open sConn

2 个答案:

答案 0 :(得分:2)

首先,您需要确保SQL Native Client已经过时。 Reference

SQL Server 2008

标准安全

Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;Uid=myUsername;
Pwd=myPassword;

可信连接

Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;
Trusted_Connection=yes;

连接到SQL Server实例 对于SQL Server的所有连接字符串,在服务器键的值中指定服务器实例的语法是相同的。

Provider=SQLNCLI10;Server=myServerName\theInstanceName;Database=myDataBase;
Trusted_Connection=yes;

Source


Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim sConnString As String
Dim recordsAffected as Long

'Create connection string
sConnString = "Provider=sqloledb; Server=LAPTOPX; Database=HomeSQL; Trusted_Connection=True;"

'Open connection and execute
conn.Open sConnString

'Do your query
With cmd
  .ActiveConnection = conn
  .CommandType = adCmdText
  .CommandText = "Select ...;"
  .Execute recordsAffected 'Includes a return parameter to capture the number of records affected
End With

Debug.Print recordsAffected 'Check whether any records were inserted

'Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set cmd = Nothing
Set conn = Nothing

答案 1 :(得分:1)

此连接字符串在Excel VBA下运行。在Ms Ms中也应该。

dbName = "test"          'your database name
dbFilePath = "C:\db.mdf" 'your path to db file

connStr = "Driver={SQL Server native Client 11.0};" & _
          "Server=(LocalDB)\v11.0;" & _
          "AttachDBFileName=" & dbFilePath & ";" & _
          "Database=" & dbName & ";" & _
          "Trusted_Connection=Yes"

完整解决方案:http://straightitsolutions.blogspot.com/2014/12/how-to-connect-to-sql-server-local.html