Joy1979 Joy1979 - 3 months ago 23
SQL Question

How to connect with two different databases by one connection string Sql and Vb.Net

I am trying to connect to database at window form level in Studio 2010/VB.Net. I am using two different databases in Sql 2008r2. One database I am using to populate records at form load event (run time) and when users pick their selection or any modification from that form, data should be updated to other database by instert, update, delete and save commands for user's future reference.

Is it possible to connect with two different databases using one Connection String?

Do I need to add two database name in below mentioned code somewhere?

Imports System.Data.SqlClient

Dim con As New SqlClient.SqlConnection("data source=DATASOURCE;initial catalog=NAME OF DATABASE;Integrated Security=True")
Dim cmd As New SqlCommand()
cmd.Connection = con
con.Open()
con.Close()


OR

Should I use two database below somewhere?

Imports System.Data.SqlClient

Public Class NEW_PERSONAL_INFORMATION

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

Dim con As New SqlClient.SqlConnection("data source=ROOM310-40\SQLEXPRESS;initial catalog=DTIS;Integrated Security=True")

Dim cmd As New SqlCommand()
cmd.Connection = con
con.Open()
con.Close()
End Sub

End Class


Apologies If I am seeking help in simple thing or not able to explain it enough.

I would appreciate any help.

Answer

I can't tell what you're asking, so I'll give two answers.

If you're trying to connect to two different servers then you'll need two different connection strings. In fact, you'll need two different SqlConnections, and you'll need to keep track of which connection is which.

Dim con1 As New SqlClient.SqlConnection("data source=ROOM310-40\SQLEXPRESS;initial catalog=DTIS;Integrated Security=True")
Dim con2 As New SqlClient.SqlConnection("data source=ROOM310-40-2\SQLEXPRESS;initial catalog=DTIS;Integrated Security=True")

If you're talking about multiple catalogs on the same server, then you don't need multiple connections. You can just specify the catalog name directly in your query:

SELECT MyColumn FROM MyDatabase1.dbo.MyTable;
SELECT MyColumn FROM MyDatabase2.dbo.MyTable;
Comments