簡體   English   中英

無法打開與SQL Server 2012的連接

[英]Could not open a connection to SQL Server 2012

HY,

我在MS Visual Studio 2012下使用SQL Server 2012。

以下是我來自app.config的連接字符串

<add key="Platform" value="Data Source=Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>

和我的聯系班

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

我的數據庫存儲在我的項目文件夾下。

嘗試使用我的方法時出現的錯誤是:

無法打開與SQL Server 2012的連接

真誠的

您的連接對象是錯誤的,您在Command中傳遞了conn ,而對於Connection open,您使用的是con對象not conn

con.Open();

采用 :

conn.Open();

您的代碼將類似於:

try
            {
                SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                conn.Open();
                cmd.ExecuteNonQuery();
             }

盡管您的代碼有一些問題,但似乎應該可以。
嘗試使用獨立的連接工具測試連接字符串。
為了測試connection string請查看此SO線程

正如@hvd在其中一條注釋中提到的那樣,您的代碼令人困惑,因為您擁有的con等同於conn 這使您的代碼難以遵循。 我建議您對其進行重構,以便您(和其他人)更容易理解。

祝好運!

嘗試這個:

<add key="Platform" value="Data Source=.\Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>

如果您的SQL Server與Visual Studio或應用程序不在同一台計算機上,則Windows防火牆中是否打開了所需的端口?

請嘗試以下步驟: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM