【问题标题】:How do I setup an ADODB connection to SQL Server 2008 in Microsoft Access 2010?如何在 Microsoft Access 2010 中设置与 SQL Server 2008 的 ADODB 连接?
【发布时间】:2014-08-12 07:27:52
【问题描述】:

我刚刚在笔记本电脑上安装了 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

【问题讨论】:

  • 您使用了错误的连接字符串,它用于连接到访问文件。您正在寻找连接到 SQL Server 2008 的连接字符串。
  • 只是一个愚蠢的问题:为什么不使用 DAO,这是 Access 中的本机方法?

标签: sql-server-2008 vba adodb


【解决方案1】:

首先,您需要确保已安装 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

【讨论】:

  • @sungod916 确保 HomeSQL 是数据库的名称,而不是 SQL Server 实例。
  • 可能希望在此答案中添加 Microsoft ActiveX 2.x 需要作为参考包含在项目中。
【解决方案2】:

此连接字符串在 Excel VBA 下工作。在 MsAccess 中也应该。

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

【讨论】:

  • 请不要只链接到可能的解决方案,而是包括相关部分。
猜你喜欢
  • 1970-01-01
  • 2011-10-28
  • 2013-03-01
  • 1970-01-01
  • 2011-09-29
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
相关资源
最近更新 更多