C#打包SQL資料庫部署安裝)

來源:互聯網
上載者:User

參考《ASP.NET與SQL一起打包部署安裝》,這篇文章是針對VB.NET與SQL 一起打包的,但是我使用的是C#,當然只要修改一下主要安裝類庫就行了!C#的類庫代碼如下:DBCustomAction.cs

using System;
using System.Collections;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Reflection;

namespace PMS
{
 /// <summary>
 /// DBCustomAction 的摘要說明。
 /// </summary>
 [RunInstaller(true)]
 public class DBCustomAction : System.Configuration.Install.Installer
 {
  /// <summary>
  /// 必需的設計器變數。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public DBCustomAction()
  {
   // 該調用是設計器所必需的。
   InitializeComponent();

   // TODO: 在 InitializeComponent 調用後添加任何初始化
  }

  private void ExecuteSql(string conn,string DatabaseName,string Sql)
  {
   SqlConnection mySqlConnection=new SqlConnection(conn);  
   SqlCommand Command=new SqlCommand(Sql, mySqlConnection);  
   mySqlConnection.Open();  
   mySqlConnection.ChangeDatabase(DatabaseName);  
   try
   {
    Command.ExecuteNonQuery();
   }  
   finally
   {
    //close Connection  
    mySqlConnection.Close();
   }
  }

  /// <summary>
  /// 清理所有正在使用的資源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  //

  public override void Install(System.Collections.IDictionary stateSaver)
  {
   base.Install(stateSaver);
  
   // ------------------------建立資料庫-------------------------------------------------
  
   try
   {
    string connstr = String.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096", Context.Parameters["server"],Context.Parameters["user"], Context.Parameters["pwd"]);
    //'根據輸入的資料庫名稱建立資料庫  
    ExecuteSql(connstr, "master", "CREATE DATABASE " +Context.Parameters["dbname"]);  
    //'調用osql執行指令碼  
    Process sqlprocess=new System.Diagnostics.Process();
    sqlprocess.StartInfo.FileName = "osql.exe ";  
    sqlprocess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -d {2} -i {3}db.sql", Context.Parameters["user"], Context.Parameters["pwd"],Context.Parameters["dbname"],Context.Parameters["targetdir"]);
    sqlprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    sqlprocess.Start();  
    sqlprocess.WaitForExit(); // '等待執行
    sqlprocess.Close();
  
    //'刪除指令檔
    FileInfo sqlfileinfo =new FileInfo(String.Format("{0}db.sql",Context.Parameters["targetdir"]));
  
    if (sqlfileinfo.Exists)
    {
     sqlfileinfo.Delete();
    }
   }
   catch(Exception ex)
   {
    throw ex;  
   }
  
   //' ---------------------將連接字串寫入Web.config-----------------------------------
  /*
   try
   {
    FileInfo fileinfo = new FileInfo(Context.Parameters["targetdir"] + "http://www.cnblogs.com/yuanlei347/admin/file://web.config/");
    if (!fileinfo.Exists)
    {
     throw new InstallException("沒有找到設定檔");
  
    }
  
    //'執行個體化xml文檔
  
    XmlDocument xmldocument=new XmlDocument();
  
    xmldocument.Load(fileinfo.FullName);
  
  
  
    //'尋找到appsettings中的節點
  
    //XmlNode node=new XmlNode();
  
    Boolean FoundIt  = false;
  
    foreach(XmlNode node in xmldocument.SelectSingleNode("appSettings").ChildNodes)
    {  
     if (node.Name == "add")
     {  
      if (node.Attributes.GetNamedItem("key").Value == "connString")
      {
       //'寫入連接字串
       node.Attributes.GetNamedItem("value").Value= String.Format("Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1",Context.Parameters["server"],Context.Parameters["dbname"], Context.Parameters["user"], Context.Parameters["pwd"]);
       FoundIt= true;  
      }  
     }  
    }
  
    if (!FoundIt)
    {  
     throw new InstallException("web.Config 檔案沒有包含connString連接字串設定");
    }   
    xmldocument.Save(fileinfo.FullName);
   }
   catch(Exception ex)
   {
    throw ex;
   } 
   */         
  }

  #region 組件設計器產生的程式碼
                 /// <summary>
                 /// 設計器支援所需的方法 - 不要使用代碼編輯器修改
                 /// 此方法的內容。
                 /// </summary>
                 private void InitializeComponent()
                 {
                  components = new System.ComponentModel.Container();
                 }
  #endregion
 }
}

我不需要修改Web.config的部分.
注意.如果不用SA使用者登入資料庫的,請先在伺服器上建立特定的SQL使用者

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.