Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can you attach more than one database to a wpf project i.e. create a connection to more than 1 database 


What I have tried:

can you attach more than one database to a wpf project i.e. create a connection to more than 1 database 
Posted
Updated 4-Jul-19 19:51pm

1 solution

Yes.
Although SqlConnection objects are scarce resources, provided that you Dispose of them when you have finished, you can create as many as you need. The simplest way is to enclose them in a using block:
C#
using (SqlConnection con = new SqlConnection(strConnectFirstDB))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("...", con))
        {
        ...
        }
    }
using (SqlConnection con = new SqlConnection(strConnectOtherDB))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("...", con))
        {
        ...
        }
    }
Or
C#
using (SqlConnection con = new SqlConnection(strConnectFirstDB))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("...", con))
        {
        using (SqlConnection con = new SqlConnection(strConnectOtherDB))
            {
            con.Open();
            using (SqlCommand cmd = new SqlCommand("...", con))
                {
                ...
                }
            }
        }
    }
Either will work fine
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900