简体   繁体   English

无法连接到 SQL 服务器

[英]Cannot connect to SQL Sever

I am new to C# and trying to connect to SQL Server for a demo query.我是 C# 的新手,并尝试连接到 SQL 服务器进行演示查询。

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.当我运行脚本时,它在 conn.Open() 处显示错误,指出找不到服务器。

When I googled it further I found that the SQL server browser should run in this case which is not there in my system.当我进一步搜索它时,我发现 SQL 服务器浏览器应该在这种情况下运行,而我的系统中没有。 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.我在 StackOverflow 上看到帖子无法连接到 sql 服务器,但它们似乎有不同的问题和解决方案。

Thanks in advance!提前致谢!

make a connection first to the DB in the visual studio by using "Server Explorer" in the left.首先使用左侧的“服务器资源管理器”连接到 Visual Studio 中的数据库。 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.拥有它后,尝试将其粘贴到 conn object。

From your comments it appears that this is your database engine is named (localdb)\LocalDataBase从您的评论看来,这是您的数据库引擎,名为(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 @ .为了在字符串中嵌入转义字符 - 您需要告诉编译器使用@逐字解释字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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