使用C#(Visual Studio 2012)连接到SQL Server 2012数据库

10

大家晚上好,

我正在尝试使用C#从SQL Server 2012数据库连接。当我使用SQL Server Management Studio时,我的连接设置如下:

Server Type:    Database Engine
Server Name:    Paul-PC\SQLEXPRESS
Authentication: Windows Authentication
Username:   Greyed out
Password:   Greyed out 

我试图连接的数据库名称是"testDB"。

这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DatabaseConnection
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = new SqlConnection("server=localhost;" +
                                       "Trusted_Connection=yes;" +
                                       "database=testDB; " +
                                       "connection timeout=30");
            try
            {
                myConnection.Open();
                MessageBox.Show("Well done!");
            }
            catch(SqlException ex)
            {
               MessageBox.Show("You failed!" + ex.Message);
            }

        }
    }
}

很遗憾,我的代码连接失败,并出现以下错误:

"You failed!A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."

有什么建议吗?SQL Server正在本地运行。


3
请确保您的SQL服务器服务正在后台运行。 - Shaharyar
1
  1. 如果您在服务器上使用(local)而不是localhost,是否会出现相同的错误?
  2. 您能否在SQL Server管理工具中打开服务器?
- Scott Chamberlain
@Shaharyar,你是什么意思?我已经检查了services.msc,SQL Server正在运行。 - thefragileomen
2
如果使用 server=(local)\\SQLEXPRESS 会发生什么?另外,您确定您正在使用 Paul-PC 吗? - Scott Chamberlain
如果你的问题已经得到解答,请考虑将其中一个答案标记为已接受。 - RyanfaeScotland
显示剩余4条评论
6个回答

6

在您的连接字符串中,将server = localhost替换为"server = Paul-PC\\SQLEXPRESS;"


3
我测试了所有这里的答案,但对我来说都没用。所以我研究了一下问题,最终找到了需要的连接字符串。要获取此字符串,您需要:
1. 在您的项目名称中:
   a. 右键单击项目名称,
   b. 点击添加,
   c. 选择 SQL Server 数据库(显然您可以将其重命名)。
   现在新的所需数据库将添加到您的项目中。
2. 数据库在“服务器资源管理器”窗口中可见。
3. 在“服务器资源管理器”窗口中单击数据库名称;现在检查“解决方案资源管理器”窗口,您将找到“连接字符串”,以及提供程序、状态、类型、版本。
4. 复制所提供的连接字符串,并将其放入 Page_Load 方法中:
string source = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();

我将我的数据库重命名为Product。同时,在“AttachDbFilename”中,您必须将“c:\ x \ x \ documents \”替换为.mdf文件物理地址的路径。

这对我有用,但我必须提醒这种方法仅适用于VS2012和VS2013。不清楚其他版本是否可行。


它只在Visual Studio 2013社区版中有效。在从属性复制连接字符串时,请不要忘记删除指向mdf文件的AttachDbFilename后面的双引号。如果将其放入连接字符串中,您将会收到异常。 - Nidhin David

0

server=.\SQLEXPRESS替换server=localhost也许可以解决问题。


谢谢Dennis。我尝试了这个,但是当我尝试编译时,Visual Studio返回了一个错误 - "未识别的转义序列"。因此,我尝试了双反斜杠,但代码仍然无法工作。 - thefragileomen
2
转义序列的问题是由于单个“/”,如果你是初学者,这个网站将是任何DBMS不同连接字符串的非常好的参考:http://www.connectionstrings.com/ - joe

0

请注意以下事项

connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";

注意:XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 & ...
你可以将"server"替换为"Data Source"。
你也可以将"database"替换为"Initial Catalog"。
示例:
 connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";

欢迎来到 Stack Overflow!请考虑在您的回答中包含一些信息,而不仅仅是发布代码。我们试图提供的不仅仅是“修复”,而是帮助人们学习。您应该解释原始代码中的问题,您做了什么不同的事情以及为什么您的更改有效。 - Andrew Barber

0

尝试:

SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");

-1
请使用这个样式。
@"server=.\sqlexpress;"

这不是正确的回答方式,请详细回答,并阅读FAQ以正确使用stackoverflow。 - Hamad
1
你可能也注意到了,几乎完全相同的答案在5个月前已经发布了。 - Andrew Barber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接