简体   繁体   中英

Cannot connect to SQL Sever

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!

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.

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 @ .

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