C#安装部署打包SQLSERVER数据库

新建一个类项目后,首先添加安装程序类:

    

写安装过程程序:

下面代码为安装过程程序,其中FrmCondition类为安装条件判断,判断电脑是否安装了SqlServer软件。Form1类为选择安装数据库。

  public override void Install(System.Collections.IDictionary stateSaver)
        {
            DialogResult DialogResult;
            System.Diagnostics.Debugger.Launch();
            string path = Context.Parameters["TARGETDIR"];

            try
            {
                base.Install(stateSaver);         
                try
                {
                    FrmCondition frmcon = new FrmCondition(path);
                    DialogResult = frmcon.ShowDialog();
                    if (DialogResult != DialogResult.OK)
                    {
                        throw new InstallException("用户取消安装!");
                    }
                }
                catch
                {
                    throw new InstallException("安装失败!");
                }

                try
                {
                    //开启sqlbrower服务,因为SqlServer默认状态下是关闭的
                    WindowsService service = new WindowsService("SQLBrowser");
                    service.StartService();
                }
                catch { }

                //数据库配置 界面
                Form1 dbFrom = new Form1();
                DialogResult = dbFrom.ShowDialog();
                if (DialogResult != DialogResult.OK)
                {
                    throw new InstallException("用户取消安装!");
                }

                CreateMydb();


            }
            catch (Exception ex)
            {

                throw new InstallException(ex.Message);
  
            }
        }


     private void CreateMydb()
        {
            string path = Context.Parameters["TARGETDIR"];
            string servername = _serverName; //服务器名字
            string dbname = _dbName;  //数据库名字
            string user = _userName; //用户名, 如‘sa’
            string pwd = _password; //相对应密码
            string Currentpath = System.IO.Directory.GetCurrentDirectory();
            string strSql = "server=" + servername + ";uid=" + user + ";pwd=" + pwd + ";database=master";//连接数据库字符串
            string strMdf = dbname + ".mdf";//MDF文件路径
            string strLdf = dbname + "_log.ldf";//LDF文件路径
            Sqldb mydb = new Sqldb();

            System.Environment.CurrentDirectory = path;
            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine;
                Microsoft.Win32.RegistryKey software =
                            key.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Lsa", true); software.SetValue("forceguest", 0);
            }
            catch { }           
            
            mydb.CreateDataBase(strSql, dbname, strMdf, strLdf, path);//开始创建数据库
            System.Environment.CurrentDirectory = Currentpath;
        }


为防止数据库文件只是可读,所以要先chmod,现将文件设置成可读
class Sqldb
    {
        public void CreateDataBase(string strSql, string DataName, string strMdf, string strLdf, string path)
        {
            SqlConnection myConn = new SqlConnection(strSql);
            String str = null;
            SqlCommand myCommand;
            try
            {
                SetChmod(strMdf);
                SetChmod(strLdf);
                str = " EXEC sp_attach_db @dbname='" + DataName + "',@filename1='" +path+ strMdf + "',@filename2='" + path + strLdf + "'";
                myCommand = new SqlCommand(str, myConn);
                myConn.Open();
                myCommand.ExecuteNonQuery();
                MessageBox.Show("数据库安装成功!点击确定继续");//需Using System.Windows.Forms
            }
            catch (Exception e)
            {
                try
                {
                    if (e.Message.IndexOf("已存在") > 0)
                    {
                        if (myConn.State == System.Data.ConnectionState.Open)
                        {
                            myConn.Close();
                        }
                        MyFile file = new MyFile();
                        string newMdf = strMdf + ".bak";
                        string newLdf = strLdf + ".bak";
                        file.CopyFile(strMdf, newMdf);
                        file.CopyFile(strLdf, newLdf);

                        str = " EXEC sp_dbremove @dbname='" + DataName + "'";
                        myCommand = new SqlCommand(str, myConn);
                        myConn.Open();
                        myCommand.ExecuteNonQuery();

                        file.MoveFile(newMdf, strMdf);
                        file.MoveFile(newLdf, strLdf);

                        str = " EXEC sp_attach_db @dbname='" + DataName + "',@filename1='" + strMdf + "',@filename2='" + strLdf + "'";
                        myCommand = new SqlCommand(str, myConn);
                        //myConn.Open();
                        myCommand.ExecuteNonQuery();
                        MessageBox.Show("数据库安装成功!点击确定继续");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("数据库安装失败!" + ex.Message + "\n\n" + "您可以手动附加数据");
                    System.Diagnostics.Process.Start(path);//打开安装目录
                }

            }
            finally
            {
                try
                {
                    myConn.Close();
                }
                catch { }
            }
        }


        public void SetChmod(string filename)
        {
            string path = @filename;
            FileInfo fi = new FileInfo(path);

            System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            fi.SetAccessControl(fileSecurity);
        }

        public void RemoveDB(string strSql, string DataName, string strMdf, string strLdf, string path)
        {
            try
            {
                SqlConnection myConn = new SqlConnection(strSql);
                String str = null;
                SqlCommand myCommand;

                myConn.Open();
                str = " EXEC sp_dbremove @dbname='" + DataName + "'";
                myCommand = new SqlCommand(str, myConn);
                myCommand.ExecuteNonQuery();
                myConn.Close();
            }
            catch { }
        }
    }

再在项目中添加安装项目



将安装所需的文件添加进去,打包安装项目即可。


我的整个安装项目览图:




  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值