How to get server name through code if SQL Server (Standard Edition) is installed

孤人 提交于 2019-12-01 18:22:27

I'm not sure I understand what you want.

If you already have a connection string, and you are trying to extract the server name from it for use elsewhere, you can reverse-engineer it like so:

var parser = new SqlConnectionStringBuilder(connectionString);
var serverName = parser.DataSource;

If you are constructing your connection string for the first time, then:

  1. If you know that you want to connect to the SQL Server on the machine that your client code is executing on, then just use (local) for the server name. If the SQL Server has an instance name, then specify it like this: (local)\myinstancename.
  2. If you don't know in advance what server to connect to, then it's up to you to obtain that information from somewhere else.

Can't you just execute SELECT @@SERVERNAME against this connection?

Is the server on the local computer?
If so, set the server name to localhost.
If not, use SqlDataSourceEnumerator.


Also, instead of building a connection string using String.Format, you should use a SqlConnectionStringBuilder. This will handle values with semicolons.

For example:

var builder = new SqlConnectionStringBuilder();

builder.UserID = dirDBinfo.UserName;
builder.Password = dirDBinfo.Password;
builder.Server= "localhost";
builder.UserID = dirDBinfo.UserName;
builder["Trusted_Connection"] = "no";
builder.Database = "TestDB"
builder.ConnectTimeout = dirDBinfo.TimeOut;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!