SqlConnection - 是远程连接还是本地连接?
如果我有 SqlConnection 对象,如何确定它是本地连接(localhost 或 127.0.0.1)还是远程连接(本地区域的其他计算机)?
How can I determine is it local connection (localhost or 127.0.0.1) or is it remote connection (other machine in local area) if I have SqlConnection object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用带有语句的连接询问 SQL
,然后验证这是否与具有 Environment.MachineName 的客户端计算机名称匹配,以 SQL 实例名称为模
Ask SQL using the connection with the statement
then verifiy if this match the name of the client machine with Environment.MachineName, modulo the SQL instance name
您可以从 SqlConnection 对象中获取连接字符串。
并检查该字符串的数据源或服务器元素。
编辑:提供了代码示例。
我认为这个功能应该可以工作(无论如何都没有测试过)。
Ps:确保在 System.Net 命名空间中添加 using 语句。
You can get the connection string out of the SqlConnection obejct.
and check the data source or the server element of that string.
Edit: Code sample provided.
I think this function should work (not tested anyways).
Ps: make sure to add a using statement to System.Net namespace.
我知道的最简单的方法是直接检查连接字符串,看看它是否包含单词 localhost、127.0.0.1、(localhost)、“.” 或本地机器名称。 检查是否以 开头,因为它们可能是正在运行的 Sql 的本地命名实例。
您可以使用 System.Environment 库来检索当前计算机名称。 您还可以考虑使用 .Net 中的 ConnectionBuilder 库来检索数据,而无需使用完整的字符串解析。 有关详细信息,请访问此处
Easiest way that I am aware of is to check the connectionstring directly to see if it contains either the words localhost, 127.0.0.1, (localhost), "." or the local machine name. Check for starting with since their could be a local named instance of Sql running.
You can use the System.Environment library to retrieve the current machine name. You can also look at using the ConnectionBuilder library in .Net to retrieve the data without using complete string parsing. Details on this can be found here
您可以检查
SqlConnection.ConnectionString
属性,看看它的server
(local) 或.
的内容> 部分,但这不是很可靠,因为%systemroot%\system32\drivers\etc\hosts' 和各种其他 SQL 别名,
foo-srv` 很可能是本地机器。You may check
SqlConnection.ConnectionString
property to see if it has something like(local)
or.
in its'server
part, but that's not very reliable because of%systemroot%\system32\drivers\etc\hosts' and various other SQL Aliases, whereby
foo-srv` may well be a local box.