博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#打包SQL数据库部署安装
阅读量:4116 次
发布时间:2019-05-25

本文共 3656 字,大约阅读时间需要 12 分钟。

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"] + "\\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用户

转载地址:http://jjupi.baihongyu.com/

你可能感兴趣的文章
如何使用更新的HTML和CSS函数创建响应式设计
查看>>
【Vue.js入门到实战教程】13-通过 Axios 发送 Ajax 请求获取接口数据渲染组件
查看>>
你应该知道的7个有用的JavaScript高阶函数
查看>>
TypeScript的索引类型与映射类型,以及常用工具泛型的实现
查看>>
震惊!针对WEB开发者华为又出新动作!
查看>>
【Vue.js入门到实战教程】14-基于 Laravel Jetstream 的Vue 技术栈编写表单组件
查看>>
process.env前端环境变量配置教程
查看>>
页面中有间隔的方格布局如何完美实现?
查看>>
javascript中数组的22种方法
查看>>
【JavaScript 教程】浏览器模型—Web Worker
查看>>
【HTML 教程】iframe
查看>>
前端JavaScript 常见的报错及异常捕获与处理方法
查看>>
Fetch API速查表:9个最常见的API请求
查看>>
【HTML 教程】表格标签
查看>>
两小时搞定ES6:原理讲解+项目实战
查看>>
15道ES6 Promise实战练习题,助你快速理解Promise
查看>>
JavaScript DOM 编程
查看>>
Vue项目打包部署总结
查看>>
CSS垂直居中,你会多少种写法?
查看>>
掌握 Promise 的逻辑方法
查看>>