开发者

How to attach a database using a program deployed by C#?

开发者 https://www.devze.com 2023-02-14 00:58 出处:网络
i wanna to attach a Database from a dynamic path to a MSSQL server by coding a project to do this,, what is the code i should write and will it be a Windows Application or Console Applicati开发者_Stac

i wanna to attach a Database from a dynamic path to a MSSQL server by coding a project to do this ,, what is the code i should write and will it be a Windows Application or Console Applicati开发者_StackOverflowon ,, or there is no difference ??


You can use any of the two. Just make sure the files are in a place the SQL Server in question can reach and then attach them with an sql statement.

Like this:

CREATE DATABASE [AdventureWorks] ON
( FILENAME = N’C:\Data\AdventureWorks_Data.mdf’ ),
( FILENAME = N’C:\Data\AdventureWorks_Log.ldf’ )
FOR ATTACH


In the connection string you can attach a database if the database has not already been attached. To do this in C# you should be able to do the following (this is untested):

    SQLConnection conn;
    try
    {
        conn = new SQLConnection(String.Format("Server={0};AttachDbFilename={1};Database=dbname; Trusted_Connection=Yes;", "Server Address", @"Path To Database"));
        conn.Open();
        conn.Close();
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        conn.Dispose();
    }

Let me know how you get on.

Regards,

Stu


Are you talking about using System.Data.SqlConnection class?

You can dynamically build your connectionString when you create your SqlConnection.


If I nderstand your question correctly, you are looking for a way to use a databse which the user will select (not the hard coded one).

Go here and learn about Saving User and Application Settings in WinForms. You will get some ideas.

0

精彩评论

暂无评论...
验证码 换一张
取 消