2013-10-01 50 views
1

我有這樣的代碼將插入到從一個表到另一個表中的數據。問題是,我現在試圖從遠程mssql服務器插入到我的本地mssql服務器的表中。如何使用VB.net的SQL腳本?連接字符串本地和遠程MSSQL SQL插入

我目前得到一個錯誤:

network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

這是我的代碼的那一刻:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 

    Dim rowsAffected As Integer = 0 


Dim myConnectionString = "Data Source=(IP Address),1433;Network Library=DBMSSOCN;Initial Catalog=dbase;User ID=sa;Password=password;" 

    Dim myconnectionstring2 = "Data Source= PC-Name;Initial Catalog=dbase;Integrated Security=True;Pooling=False" 

    'Dim myConnection As New SqlConnection(myConnectionString) 





    Dim myQuery As String = "INSERT INTO dbase.dbo.tbltransactions1 SELECT * FROM dbase.dbo.tbltransactions1" 

    'Dim myQuery As String = "insert INTO (table)" 

    'select 

    'from LinkedserverName.DatabaseName.SchemaName.TableName" 

    Dim myCommand As New SqlCommand(myQuery, myConnection, myConnection2) 



    Try 

     myConnection.Open() 

     rowsAffected = myCommand.ExecuteNonQuery() 

    Catch ex As Exception 

     MsgBox(" ") 

    Finally 

     myConnection.Close() 

    End Try 



    Label1.Text = rowsAffected.ToString() 
End Sub 

*擁有一個IP地址的連接字符串是我要連接的服務器而另一個是我的本地服務器的連接字符串..

+0

你得到一個錯誤訊息? –

+0

是的..我做錯誤消息是:建立到SQL Server的連接時發生網絡相關或實例特定的錯誤。服務器未找到或無法訪問。驗證實例名稱是否正確,並將SQL Server配置爲允許遠程連接。 (提供程序:TCP提供程序,錯誤:0 - 連接嘗試失敗,因爲連接方在一段時間後沒有正確響應,或者由於連接的主機未能響應而建立連接失敗。) –

回答

1

你最好的鏡頭是Linked Server指向遠程服務器的本地服務器。

另一種方法是以DataTable爲例,獲取本地遠程數據,然後將其從DataTable推送到本地數據庫。

當前您正在訂購本地sql以與遠程服務器進行通信。如果不設置Linked Server,則不會發生這種情況。

爲了建立一個Linked Server

  1. 打開SSMS並連接到本地服務器。
  2. 展開您的服務器節點。
  3. 展開Server Objects
  4. Right Click on Linked Servers
  5. 選擇New Linked Server
  6. 類型的Server Name
  7. 選擇SQL Server
  8. 遠程服務器的IP在Security選項卡中添加一個登錄映射。您將不得不爲遠程服務器提供憑據。
  9. Local Login列中,添加用於連接到Local Server的用戶名。
  10. 離開Impersonate山坳選中如果憑據到遠程服務器是比本地服務器的有所不同(這應該是這種情況)
  11. 輸入用戶名和你用來登錄到Remote Server密碼分別在Remote UserRemote Password之下。
  12. 出於安全原因,我會在該選項卡底部的收音機組中選擇Not Be Made

然後你就可以運行類似的查詢:

SELECT * FROM [RemoteServerIP].[RemoteServerDB].[RemoteServerSchema].[RemoteServerTable] 
+0

謝謝先生..要嘗試這個! –

+0

Sir在安全選項卡中跟進有關登錄映射的問題。我應該使用什麼登錄名?我在本地服務器上登錄? –

+0

檢查更新plz。 –