简体   繁体   English

使用Excel VBA中的ADO通过网络连接到SQL Server

[英]Connecting to SQL Server over network using ADO from Excel VBA

I need to connect to a SQL Server DB running on my laptop from another computer on a network. 我需要从网络上的另一台计算机连接到我的笔记本电脑上运行的SQL Server数据库。 I am doing this both from a C# app as well as in a VBA macro. 我是从C#应用程序以及VBA宏中执行此操作。 Both run perfectly on my laptop and the C# app runs perfectly over the network. 两者都在我的笔记本电脑上完美运行,而C#应用程序在网络上运行完美。 However I cannot connect using VBA over the network. 但是我无法通过网络使用VBA进行连接。 This is my connection string: 这是我的连接字符串:

ConnectionString = "Driver={SQL Server};Server=MY-LAPTOP; DAtabase=SAFEXlive; UID = MyUsername; PWD=MyPassword"

Aside from the 'Driver={SQL Server}' this is the same as the connection string I am using in the C# app which works. 除了'Driver = {SQL Server}'之外,这与我在C#app中使用的连接字符串相同。

I am then using the following code (With a reference to Microsoft ActiveX Data Objects 6.0 Library in VBE) to open the connection: 然后我使用以下代码(在VBE中引用Microsoft ActiveX Data Objects 6.0库)打开连接:

Dim oConnection As Connection
Set oConnection = New Connection
oConnection.ConnectionString = strConnectionString
oConnection.Open

This works correctly if I run it on my laptop but if I run it on another computer on the network I get the error: "Run-time error '-2147217843 (80040e4d) [Microsoft][ODBC Server Driver][SQL Server]Login failed for user..." and the user it specifies it the windows log in for the computer. 如果我在我的笔记本电脑上运行它,这是正常的,但如果我在网络上的另一台计算机上运行它我得到错误:“运行时错误'-2147217843(80040e4d)[微软] [ODBC服务器驱动程序] [SQL Server]登录用户失败...“并且用户指定它登录计算机的Windows。

Are there some security settings I need to set in code or in excel? 我需要在代码或excel中设置一些安全设置吗? Or am I constructing the connection string incorrectly? 或者我是否错误地构造连接字符串? What am I doing wrong? 我究竟做错了什么?

Solved. 解决了。 The answer is rather infuriating. 答案是相当令人愤怒的。 The problem is in fact with the connection string, with the UID. 问题实际上是连接字符串和UID。 Believe it or not changing ...UID= MyUsername;... to ..UID=MyUsername;... , ie removing the space character, was all it took! 信不信由你...UID= MyUsername;... to ...UID= MyUsername;... ..UID=MyUsername;... ,即删除空格字符,就是这么多! Thanks for suggestions though. 谢谢你的建议。

Try this Connection string, 试试这个连接字符串,

ConnectionString = "Provider=SQLOLEDB;Data Source=MY-LAPTOP;Initial Catalog=SAFEXlive;User ID=MyUsername;Password=MyPassword"

Is this an AD Domain login? 这是AD域名登录吗? Make sure you have appended the domain to the username eg, domain\\user\u003c/code> . 确保您已将域附加到用户名,例如domain\\user\u003c/code> 。 I suggest using integrated security instead of this. 我建议使用集成安全性而不是这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM