在SQL服务器上建立和备份、恢复数据库的C#代码(源于WEBCAST:在智能客户端应用程序中部署SQL Server 2005)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;


using Microsoft.SqlServer.Management.Smo;         //必先添加Microsoft.SqlServer.ConnectionInfo、
                                                  
//Microsoft.SqlServer.Smo、Microsoft.SqlServer.SmoEnum等引用
using Microsoft.SqlServer.Management.Common;

namespace SMO_Solution
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }




        
private void btnConnect_Click(object sender, EventArgs e)
        
{
            
//Server srv = new Server(Environment.MachineName);
            
//MessageBox.Show("The AdventureWorksDW database was created at " + srv.Databases["AdventureWorksDW"].CreateDate.ToString());

            ServerConnection conn 
= new ServerConnection();
            conn.LoginSecure 
= false;
            conn.Login 
= "username";
            conn.Password 
= "password";
            Server svr 
= new Server(conn);
            Console.WriteLine(svr.Name 
+ " " + svr.Information.VersionString);

        }


        
/// <summary>
        
/// 建立数据库及表及字段
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        private void btnDBTableCreate_Click(object sender, EventArgs e)
        
{
            Server srv 
= new Server(Environment.MachineName);
            Database smoDB 
= new Database(srv, "SMO_DB");
            smoDB.Create();

            Table smoTBL 
= new Table(smoDB, "SMO_TBL");
            Column smoCol1 
= new Column(smoTBL, "c1", DataType.Int);
            smoTBL.Columns.Add(smoCol1);

            Column smoCol2 
= new Column(smoTBL, "c2", DataType.NVarChar(30));
            smoTBL.Columns.Add(smoCol2);

            smoTBL.Create();

            MessageBox.Show(
"Database and Table Created!");

        }


        
/// <summary>
        
/// 备份数据库及进行备份校验
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        private void btnBackup_Click(object sender, EventArgs e)
        
{
            Server srv 
= new Server(Environment.MachineName);
            BackupDeviceItem backDeviceItem 
= new BackupDeviceItem(@"C:\Webcast\SMO_BACKUP.bak", DeviceType.File);
            Backup back 
= new Backup();

            back.Database 
= "AdventureWorksDW";
            back.Devices.Add(backDeviceItem);
            back.Action 
= BackupActionType.Database;
            
//bkp.Action = BackupActionType.Files;
            
//bkp.DatabaseFileGroups.Add("WorkOrderGroup");
            back.SqlBackup(srv);

            MessageBox.Show(
"Backup Complete!");

            Restore rest 
= new Restore();
            BackupDeviceItem restDeviceItem 
= new BackupDeviceItem(@"C:\Webcast\SMO_BACKUP.bak", DeviceType.File);

            rest.Devices.Add(restDeviceItem);
                  
//以下两排为恢复数据库代码
                  
//rest.Action = RestoreActionType.Database;
                  
//rest.SqlRestore(srv)

            
bool verified = rest.SqlVerify(srv);
          

            
if(verified == true)
            
{
            MessageBox.Show(
"The backup was verified scuuessfully");
            }

            
else
            
{
            MessageBox.Show(
"The backup is corrupt");
            }


        }



        
private void btnCheckCatalog_Click(object sender, EventArgs e)
        
{
            Server svr 
= new Server(Environment.MachineName);
            Database db;
            db 
= svr.Databases["AdventureWorksDW"];

            StringCollection sc;
            sc 
= db.CheckCatalog();

            
for (int i = 0; i < sc.Count; i++)
            
{
                
if (sc[i].Length > 0)
                
{
                    MessageBox.Show(sc[i]);
                }
   
            }


            

        }


        
/// <summary>
        
/// 输出脚本或存储过程
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        private void btnScripter_Click(object sender, EventArgs e)
        
{
            
//输出脚本

            Server srv 
= new Server(Environment.MachineName);
            Scripter scr 
= new Scripter(srv);

            scr.Options.FileName 
= @"C:\Webcast\scripter.txt";
            scr.Options.AppendToFile 
= true;
            scr.Options.IncludeHeaders 
= true;

            Database db 
= srv.Databases["AdventureWorksDW"];
            SqlSmoObject[] smoObjects;

            smoObjects 
= new SqlSmoObject[db.Tables.Count];

            
int i = 0;
            
foreach (Table tbl in db.Tables)
            
{
                
if (tbl.IsSystemObject == false)
                
{
                    smoObjects[i] 
= tbl;
                    i
++;
                }

            }


            SqlSmoObject[] newSmoObjects;

            newSmoObjects 
= new SqlSmoObject[i];

            
for (int j = 0; j < i; j++)
            
{
                newSmoObjects[j] 
= smoObjects[j];
            }

            scr.Script(newSmoObjects);
            MessageBox.Show(
"Scripting complete!");



            
//输出存储过程

            
//Server svr = new Server(Environment.MachineName);
            
//StoredProcedure sp = svr.Databases["AdventureWorksDW"].StoredProcedures["sp_statistics", "sys"];

            
//ScriptingOptions so = new ScriptingOptions();
            
//so.IncludeHeaders = true;
            
//so.SchemaQualify = true;

            
//foreach (string s in sp.Script(so))
            
//{
            
//    MessageBox.Show(s);
            
//}
        }

    }

}
原文地址:https://www.cnblogs.com/ahuang1118/p/838517.html