使用C# Detach和Attach 資料庫

來源:互聯網
上載者:User

先上一個使用SQL 陳述式進行Detach和Attach資料庫的語句:

use mastergosp_detach_db 'TestDB'go                                                                                                                use mastergosp_attach_db '1','C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB.mdf','C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB_log.ldf'go

用C#進行Detach和Attach資料庫,我想到的有兩種方法

1. 用SqlCommand執行上述語句,代碼如下:
using(SqlConnectionsc =newSqlConnection(txtConntionString.Text))
{
   using(SqlCommandcmd =newSqlCommand(@"use master;
            exec sp_detach_db 'TestDB'", sc))
    {
        if(sc.State ==ConnectionState.Closed)
             sc.Open();

         cmd.CommandType =CommandType.Text;
         cmd.ExecuteNonQuery();
    }
}

using(SqlConnectionsc =newSqlConnection(txtConntionString.Text))
{
   using (SqlCommandcmd =newSqlCommand(@"use master;
                         exec sp_attach_db 'TestDB'
                         ,'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB.mdf'
                         ,'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB_log.ldf'", sc))
   {
        if(sc.State ==ConnectionState.Closed)
            sc.Open();

        cmd.CommandType =CommandType.Text;
        cmd.ExecuteNonQuery();
   }
}

需要注意的是SQL語句中的go在這裡換成了分號,SQL語句中不加exec也可以正常執行,而這裡必須加入exec
因為用到了SqlConnection,所以必須指定一個有效串連字串,在Detach時可以用TestDB這個資料庫作串連字串,但是在Attach時,就不用TestDB了,因為還未建立,這點在寫代碼時要注意,當然如果串連字串中使用的是master資料庫,那use master也可以省了

2. 使用SQL Server內建的Attach和Detach功能
這裡有用到SQL Server提供的幾個Dll
先加引用:
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
命名空間加:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Collections.Specialized;

代碼如下:
ServerConnection sc = new ServerConnection("ServerNameHere");//You can specify username and password here
Server server = newServer(sc);
server.DetachDatabase("TestDB",false);

ServerConnection sc = new ServerConnection("ServerNameHere");//You can specify username and password hereServer server = new Server(sc);
StringCollection files = new StringCollection();files.Add(@"C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB.mdf");files.Add(@"C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB_log.ldf"); server .AttachDatabase("TestDB", files, AttachOptions.None);

在執行完後可以調用Server的Disconnect方法關閉串連。

在detach和attach資料庫時有一些選項,可以根據需要自己指定。

更新:

查看SQL Server協助文檔得知 sp_attach_db在今後可能棄用,建議使用create database,樣本如下:

USE master;GOsp_detach_db Archive;GO-- Get the SQL Server data pathDECLARE @data_path nvarchar(256);SET @data_path = (SELECT SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1)                  FROM master.sys.master_files                  WHERE database_id = 1 AND file_id = 1);-- Execute CREATE DATABASE FOR ATTACH statementEXEC ('CREATE DATABASE Archive      ON (FILENAME = '''+ @data_path + 'archdat1.mdf'')      FOR ATTACH');GO

 

不過目前在SQL Server 2008中sp_attach_db還是可以正常使用的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.