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);
            }

        }
    }
}

不幸的是,我的代码无法连接并出现以下错误:-

“您失败了!建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 "

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

4

6 回答 6

6

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

于 2013-06-23T21:03:54.223 回答
3

我在这里测试了所有答案,但对我来说,没有一个有效。于是我研究了一下问题,终于找到了需要的连接字符串。要获取此字符串,您可以:
1. 在您
的项目名称中:右键单击项目名称,
b。单击添加,
c。选择 SQL Server 数据库(显然您可以根据需要重命名它)。
现在,新的所需数据库将添加到您的项目中。
2. 数据库在服务器资源管理器窗口中可见。
3.在Server Explorer窗口左键单击数据库名称;现在检查解决方案资源管理器窗口,您会发现“连接字符串”以及提供者、状态、类型、版本。
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。其他版本不知道。

于 2014-01-14T15:24:07.120 回答
0

注意下

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

注:XXX = 。OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...

您可以用“数据源”替换“服务器”

你也可以用'初始目录'替换'数据库'

样本:

 connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";
于 2014-12-10T20:19:02.447 回答
0

尝试:

SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");
于 2013-06-23T21:06:44.957 回答
0

替换server=localhostserver=.\SQLEXPRESS可能会完成这项工作。

于 2013-06-23T20:42:14.413 回答
-1

use this style

@"server=.\sqlexpress;"
于 2013-11-21T12:51:13.803 回答