![](/img/trans.png)
[英]Connection to SQL Server Database inside Visual Studio 2012 C#
[英]Connect to SQL Server 2012 Database with C# (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的连接时发生了与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。请验证实例名称正确并且将SQL Server配置为允许远程连接。 ”
有什么建议么? SQL Server在本地运行。
在您的连接字符串中,将server=localhost
替换为“ server = Paul-PC\\\\SQLEXPRESS;
”
我在这里测试了所有答案,但是对我来说,没有一个有效。 所以我研究了一下问题,最后我找到了需要的连接字符串。 要获取此字符串,请执行以下操作:
1.在您的项目名称中:
一种。 右键单击项目名称,
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();
我将数据库重命名为“产品”。 另外,在“ AttachDbFilename”中,必须将“ c:\\ x \\ x \\ documents \\”替换为.mdf文件物理地址的路径。
它为我工作,但我必须提到此方法适用于VS2012和VS2013。 不了解其他版本。
用server=.\\SQLEXPRESS
替换server=localhost
可能会完成这项工作。
尝试:
SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");
注意下
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;"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.