2012-06-01 46 views
0

我用下面的連接字符串錯誤在C#中訪問數據庫

static string appath = Library_Records.Program.app_path; 

string connectionstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=appath;Integrated Security = true;User Instance = True"; 
connection = new SqlConnection(connectionstring); 

static string dbfiles = null; 
internal static string app_path 
{ 
    get { return dbfiles = "|Datadirectory|\\5700.mdf"; } 
} 

Library_Records訪問基於服務數據庫:命名空間,程序是包含Main()

當我打電話connection.Open()類的名稱,它給出以下錯誤

嘗試爲文件appath附加自動命名的數據庫失敗。 A 數據庫中存在相同的名稱,或者指定的文件不能被 打開,或者它位於UNC共享上。

5700是我的數據庫與.mdf擴展名。如何糾正這個問題?

回答

3

變量永遠不會被字符串中的值自動替換,因此AttachDbFilename=appath;將不起作用。

你應該這樣做:

string connectionstring = 
    string.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath); 

connection = new SqlConnection(connectionstring); 
+0

它的工作三江源先生現在,如果我創建一個安裝文件(.exe),然後將數據庫是任何其他計算機上訪問,因爲我首先創建一個設置在AttachDbFilename = C:\ Users \ Sarao \ Documents \ prjs \ Library_Records \ Library_Records \ 5700.mdf當我在另一臺計算機上運行它時,它表示該數據庫不可訪問,隨後是路徑 – jaggi

+0

只要將數據庫文件複製到另一臺計算機與您的計劃一起 - 它應該工作。 –