[英]Could not open a connection to SQL Server 2012
Hy, HY,
I am using SQL Server 2012 under MS Visual Studio 2012. 我在MS Visual Studio 2012下使用SQL Server 2012。
Below is my connection string from app.config 以下是我来自app.config的连接字符串
<add key="Platform" value="Data Source=Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>
and my connection class 和我的联系班
static SqlConnection con;
public static SqlConnection GetConnection()
{
con = new SqlConnection(ConfigurationManager.AppSettings["Platform"].ToString());
return con;
}
internal void AddCustomer (Buyer customer, User user, PlatformType type )
{
SqlConnection conn = DALConnection.GetConnection();
try
{
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
...
con.Open();
cmd.ExecuteNonQuery();
My database is stored under my project folder. 我的数据库存储在我的项目文件夹下。
The error I get when I try to use my method is: 尝试使用我的方法时出现的错误是:
Could not open a connection to SQL Server 2012
无法打开与SQL Server 2012的连接
Sincerely, 真诚的
Your connection object is wrong, you are passing conn
in Command while for Connection open you are using con
object not conn
: 您的连接对象是错误的,您在Command中传递了
conn
,而对于Connection open,您使用的是con
对象not conn
:
con.Open();
use : 采用 :
conn.Open();
you code will be like: 您的代码将类似于:
try
{
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
}
Although your code has some issues, It seems that it should work. 尽管您的代码有一些问题,但似乎应该可以。
Try testing your connection string using an independent tool for connectivity. 尝试使用独立的连接工具测试连接字符串。
For testing the connection string
take a look at this SO thread . 为了测试
connection string
请查看此SO线程 。
As @hvd has mentioned in one of the comments, your code is confusing as you have con
which is equivalent to conn
. 正如@hvd在其中一条注释中提到的那样,您的代码令人困惑,因为您拥有的
con
等同于conn
。 this makes your code hard to follow. 这使您的代码难以遵循。 I recommend you refactor it so it will be easier for you (and others) to follow.
我建议您对其进行重构,以便您(和其他人)更容易理解。
Good luck! 祝好运!
尝试这个:
<add key="Platform" value="Data Source=.\Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>
If your SQL Server is on a different machine than your Visual Studio or app, are the required ports open in the Windows Firewall ? 如果您的SQL Server与Visual Studio或应用程序不在同一台计算机上,则Windows防火墙中是否打开了所需的端口?
Try these steps: http://blog.sujay.sarma.in/2013/12/19/SCRIPT-Open-ports-in-Windows-Firewall-for-SQL-Server-connectivity 请尝试以下步骤: http : //blog.sujay.sarma.in/2013/12/19/SCRIPT-Open-ports-in-Windows-Firewall-for-SQL-Server-connectivity
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.