如何使用 SMO 建立資料庫(Database)

除了使用 T-SQL 的 CREATE DATABASE 來建立資料庫外,也可以使用 SMO 來建立資料庫。

 

筆者使用一個 Console 應用程式來說明:

1. 使用 Visual Studio 建立一個 Console 應用程式

2. 引用 Microsoft.SqlServer.ConnectionInfo、Microsoft.SqlServer.Management.Sdk.Sfc、Microsoft.SqlServer.Smo

3. 範例程式如下:

 using System; 
using System.Data; 
using System.Data.SqlClient; 

using Microsoft.SqlServer.Management.Smo; 

namespace UsingSmoCreateSQLServerDatabase 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // 使用 SMO 建立資料庫 
            Server server = new Server("(local)\\SQLExpress"); 
            Database db = new Database(server, "SmoDatabase"); 
            db.Create(); 
            Console.WriteLine("=> 資料庫 {0} 已建立", db.ToString()); 

            Console.ReadKey(); 

        } 
    } 
}

 

執行結果:

image

 

Hope this helps.