简体   繁体   中英

C# Connecting to a SQL server with a named instance?

A client of mine has told me the program I made for them won't connect to a SQL server named instance, I have a standard SQL server with no named instance so I'm wondering how I can test this. A named instance connection string look like the one below, could the backslash be were my code fails?

Driver={SQL Native Client};Server=myServerName\\theInstanceName;Database=myDataBase;

My code is as follows:

sqlServer=s.Substring(keyword.Length,s.Length-keyword.Length);
FormODBC formODBC=new FormODBC(this);
formODBC.SetSqlServer(sqlServer,dbUsername,dbPassword,database,table);
formODBC.ReadData();

How should I handle the backslash as I suspect this may be the problem?

Thanks

We have SQL servers with named instances. Examples: myservername\\sql2005. Backslash is fine, in the conection string server name will be "myservername\\sql2005", works 100% fine. You can have a "regular instance" on the same server, will be "myservername"

PS just unit test your function making connection string returns "myservername\\sql2005".

Also, remember that backslash is an escape character in C# strings. If your instance name is contained in a string variable, make sure you do either:

string server = "myServer\\myInstance";

or

string server = @"myServer\myInstance";

The answer is to ensure your connection string is configurable, and set it to something like:

data source=localhost\\msexpress;database=dbname;trusted_connection=true;

Scott, At the risk of stating the obvious, have you tried setting up a named instance in your own development environment? I don't actually know the answer to your question but I've never personally run into a solution where testing the scenario that is failing directly didn't help. At a minimum you ought to be able to get better debugging information as to precisely what is failing. Good luck getting this resolved.

Regards, Chris

There is also the occassional SQL Express edition case where the name is MyServerName\\SQLEXPRESS. This can trip up some people because they wouldn't think to specify the server that way.

You can extract your connection string to a config file (note this isn't necessarily secure - that will depend on how their SQL security server is set up and the account your application is running under) - then your client can just add the appropriate connection string for their server to your application's config when deployed.

Notes:

  • You can create a connection string by renaming a .txt file to a .udl file and running through until you can connect to your/their server.
  • Your unamed instance can actually be accessed by name - the machine name on which the SQL server is installed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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