0

I am new to C# and trying to connect to SQL Server for a demo query.

This is my shortcode for the same.

SqlConnection conn = new SqlConnection("data source=.; database=Sample; integrated security=SSPI");

SqlCommand cmd = new SqlCommand("select * from employees", conn);

conn.Open();

when I am running the script it is showing error at conn.Open() stating that cannot find the server.

When I googled it further I found that the SQL server browser should run in this case which is not there in my system. Any idea how can I make it reach the server?

I saw posts on StackOverflow Cannot connect to sql server but they seem to have different issue and solution.

Thanks in advance!

webDC
  • 17
  • 7
  • Are you able to connect to it with SSMS? – mjwills Jul 24 '20 at 09:16
  • I assume the server is on your local machine? Try use "(local)" instead of . as the data source. – Murray Foxcroft Jul 24 '20 at 09:18
  • Did you follow the required steps to allow communication with your database? https://stackoverflow.com/questions/9138172/enable-tcp-ip-remote-connections-to-sql-server-express-already-installed-databas – Steve Jul 24 '20 at 09:23
  • What version of Sql Server do you use? Full, Express, or LocalDB? See here https://stackoverflow.com/a/20218301/5045688 how to define name. – Alexander Petrov Jul 24 '20 at 09:36
  • Although the SQL Server Browser service is not needed for the connection string in your question (default local instance), that fact it doesn't exist suggests SQL Server may not be installed. Make sure SQL Server is installed and the service running. Of course, you also need to attach or restore the Sample database referenced in the connection string. – Dan Guzman Jul 24 '20 at 09:43
  • @ziakhan I have only SQL server VSS writer service runnig no other instances. – webDC Jul 24 '20 at 14:20
  • If you are using LocalDB, the connection string must contain `(localdb)\MSSQLLocalDB`. – Alexander Petrov Jul 24 '20 at 20:54

2 Answers2

0

make a connection first to the DB in the visual studio by using "Server Explorer" in the left. Then press "Connect to a Database" and then once you are connected, look for the properties of the DB and pick the Connection string attribute. Once you have it try pasted it the conn object.

  • I tried the same and the string is this Data Source=(localdb)\LocalDataBase but it is throwing compile-time error as "\" unrecognized escape character – webDC Jul 24 '20 at 14:15
0

From your comments it appears that this is your database engine is named (localdb)\LocalDataBase

If so your connection string will be:

        SqlConnection conn = new SqlConnection(@"data source=(localdb)\LocalDataBase; database=Sample; integrated security=SSPI");

In order to embed an escape character within a string - you need to tell the compiler to interpret the string literally by using the @.

Alex Leo
  • 2,781
  • 2
  • 13
  • 29