2015-09-07 52 views
1

我這裏有一個工作的SQL連接:C#Windows應用程序attachmentFilename

SqlConnection conn = 
    new SqlConnection(@"server=localhost\SQLEXPRESS; 
         AttachDbFilename=C:\Seach ENGINE (June 22, 2015)\SE\SE\MainDatabase.mdf; 
         Integrated Security=True;User Instance=True"); 

,但問題是我需要提供完整路徑。不像asp.net,所有我需要做的就是添加|DataDirectory|它和包括數據庫名..

然後我嘗試這個連接字符串中使用|DataDirectory|和我得到一個錯誤:

invalid value for key 'attachDbFilename'

我出版了我的應用程序,因爲我在不同的計算機安裝了它,我現在不能定位數據庫..所以attachDbFilename是不正確的..

如果DataDirectory不工作是否有任何其他的代碼,我可以使用類似於數據目錄?

+0

兩臺機器都已連接? – Sunny

+0

是的,先生..多數民衆贊成在 – kaizoshi

+0

爲什麼你不使用IP? – Sunny

回答

0

SqlConnection要求您指定要連接的db的 db的完全限定名稱。
沒辦法。

1

AttachDbFilename與本地數據庫一起使用。如果您有遠程數據庫,則連接字符串將爲be different。看看文章 - How to configure SQL Server 2005允許遠程連接。

Access mdf file

正如你在這裏看到的

System.Data.SqlClient resolves the substitution strings into full paths against the local computer file system. Therefore, remote server, HTTP, and UNC path names are not supported. An exception is thrown when the connection is opened if the server is not located on the local computer.

如果你想連接到一個已經運行的SQL Server Express實例的另一臺計算機通過TCP上,那麼你需要建立TCP連接上該服務器第一。請注意,您不能使用AttachDbFilename,因爲該選項僅適用於SQL Server Express的「用戶實例」。

希望這會幫助你。