简体   繁体   中英

Connecting a SQL Server .bak backup file to Visual Studio

My problem over here is that I have backed up my SQL Server database SDP , then I restored the backup file on another PC.

Now I would like to execute my vb.net program from the new PC. The problem I am facing is that the server name I have written in my code is the server name of my previous PC ("servernamePC1"). On the new PC, the server name is different. Hence, how to set a universal connection path in vb.net to connect to my database?

Dim con As New SqlConnection("server = servernamePC1; database=SDP; integrated security=SSPI")

The server name I have specified above is a sample server name - not the actual server name. Assume that the server name ("servernamePC1") is the first PC's server name. Now I have to connect to the database on a new PC with a different server name. Is that possible? Or do I have to set a universal path?

There is no such thing as an "universal" path or anything.

Such differences in server (and possibly database) name are the main reason the generally accepted Best Practice is to put these kinds of things into editable .config files - so you can adapt those connection strings (and other items) to varying environments and setups, without having to recompile your code to pick up the change.

So in your case, use an app.config or web.config file in your project, and then add your connection string to that config file:

<configuration>
    <connectionStrings>
        <add name="YourDatabase" 
             connectionString="server=servernamePC1;database=SDP;integrated security=SSPI"
             providerName="System.Data.SqlClient"/>  
    </connectionStrings>
</configuration>

Now, on your second PC, you just need to adapt this config file.

You read out this config file using the ConfigurationManager class in .NET:

using System.Configuration;

public void YourMethod() 
{
    string connectionString = ConfigurationManager.ConnectionStrings["YourDatabase"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        // do your stuff here
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM