2015-04-04 105 views
-2

我使用下面的代碼從c#.net中的數據庫創建備份。但是當我運行代碼我得到這個錯誤:ServerConnection不適用於連接字符串

未能連接到服務器數據源= .;初始目錄= AngularJs;集成安全=真。

我的代碼來做到這一點:

ServerConnection con = new ServerConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True"); 
     Server server = new Server(con); 
     Backup source = new Backup(); 
     source.Action = BackupActionType.Database; 
     source.Database = drpDatabases.SelectedItem.ToString(); 
     BackupDeviceItem destination = new BackupDeviceItem(Path, DeviceType.File); 
     source.Devices.Add(destination); 
     source.SqlBackup(server); 
     con.Disconnect(); 

在哪裏的問題?爲什麼這不起作用? 我用sqlconnection測試了連接字符串,它的工作正常並且打開得很好。

+1

我的猜測是txtServerName.Text中填充了一個「。」並正在查找服務器名稱。 – Bob 2015-04-04 17:55:23

+0

是文本服務器=。 ;這是錯的嗎? – 2015-04-04 17:57:59

+0

我通常會看到Data Source = ServerName – Bob 2015-04-04 17:59:07

回答

0

你的代碼是錯誤的,使用方法:

ServerConnection con = new ServerConnection(
    new SqlConnection(
     "Data Source=" + txtServerName.Text + ";Initial Catalog=" 
     + drpDatabases.SelectedItem.ToString() 
     + ";Integrated Security=True")); 
+0

您應該解釋[ServerConnection(String)](https://msdn.microsoft.com/en-us/library/ms191560.aspx)需要實例名稱,而不是連接字符串。 OP還可以寫入'新的ServerConnection(txtServerName.Text)'。 – 2015-04-06 09:38:56

0

ServerConnection(string)超載期待一個實例名稱,而不是一個連接字符串。你可以簡單地寫new ServerConnection(".")或:

var con = new ServerConnection(txtServerName.Text); 

錯誤消息告訴你,ServerConnection試圖連接到具有名稱相同整個連接字符串來連接服務器和失敗。

ServerConnection表示與特定服務器的連接,而不是數據庫,因此它不需要SqlConnection對象。如果您提供一個,它僅用於提取相關信息。

0

試試這個:

SqlConnection con = new SqlConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True"); 
SeverConnection scon = new ServerConnection(con); 
Server svr = new Server(scon); 

,因爲我認爲你傳遞不正確的參數爲一個ServerConnection。