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

晚上好,

我正在尝试从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的连接时发生了与网络相关或特定于实例的错误。未找到服务器或无法访问服务器。validation实例名称是否正确以及SQL Server是否配置为允许远程连接。 “

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

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

我在这里测试了所有的答案,但对我来说,没有人工作。 所以我研究了一下这个问题,最后我找到了所需的连接字符串。 要获得此字符串,您可以:
1.在您的项目名称中:
一个。 右键单击项目名称,
湾 点击添加,
C。 选择SQL Server数据库(显然您可以根据需要重命名)。
现在,新的所需数据库将添加到您的项目中。
2.数据库在“服务器资源管理器”窗口中可见。
3.在“服务器资源管理器”窗口中单击数据库名称; 现在查看Solution Explorer窗口,您将找到“Connection String”,以及Provider,State,Type,Version。
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。 不知道其他版本。

尝试:

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

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

注意下

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

注意:XXX =。 或。\ SQLEXPRESS或。\ MSSQLSERVER或(本地)\ SQLEXPRESS或(localdb)\ v11.0&…

你可以用’ 数据源 ‘替换’ 服务器

您也可以用’ 初始目录 ‘替换’ 数据库

样品:

  connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;"; 

使用这种风格

 @"server=.\sqlexpress;"