最近在做项目时,将软件打包给技术部门用,里面因为用到数据库,所以最好是在安装文件执行完毕之后,自动还原数据库(sql)

想到了2个方法

  1. 做成安装包(自定义安装,用数据库备份文件还原)
  2. 利用sql脚本,生成,但osql还是有限制

这2个方法都是可行的,第二个方法会出现多个文件,第一个方法只有一个安装包;

显然一个方法方便些;

实现思路:

  1. 找到数据库备份文件
  2. 安装时还原数据库
  3. 卸载时删除数据库

重写 public override void Install(IDictionary stateSaver)和public override void Uninstall(IDictionary savedState)方法

自己编写好代码,编译运行,安装,却出现1001错误,找不到数据库备份文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration.Install;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Diagnostics;

namespace SmartHomeSetup
{
    [RunInstaller(true)]
    public class Form1 : System.Configuration.Install.Installer
    {
        private System.ComponentModel.Container components = null;
        public Form1()
        {
            InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

//返回路径       

private static string PrepareSQL(string name)
        {
            string tempfile = "";
            try
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                Stream fs = asm.GetManifestResourceStream(asm.GetName().Name + "." + name);
                BinaryReader br = new BinaryReader(fs);

                tempfile = Path.GetTempFileName();
                FileStream fsWrite = new FileStream(tempfile, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fsWrite);
                byte[] data = br.ReadBytes(1024);
                while (data != null && data.Length > 0)
                {
                    bw.Write(data);
                    data = br.ReadBytes(1024);
                }

                br.Close();
                fs.Close();
                bw.Close();
                fsWrite.Close();
            }
            catch (System.Exception e)
            {
                throw e;
            }

            return tempfile;
        }

        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
            //创建数据库的连接字符串
            string DbConnection =
                "Server=" + Context.Parameters["databaseServer"] + ";" +
                "Trusted_Connection=true;" +
                "U>

重新编译,安装OK

相关文章:

  • 2022-12-23
  • 2022-01-11
  • 2021-06-14
  • 2022-01-11
  • 2022-12-23
  • 2022-02-26
  • 2022-12-23
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
相关资源
相似解决方案