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

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

26人阅读 评论(1) 收藏 举报

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

    

写安装过程程序:

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

  1. public override void Install(System.Collections.IDictionary stateSaver)  
  2.       {  
  3.           DialogResult DialogResult;  
  4.           System.Diagnostics.Debugger.Launch();  
  5.           string path = Context.Parameters["TARGETDIR"];  
  6.   
  7.           try  
  8.           {  
  9.               base.Install(stateSaver);           
  10.               try  
  11.               {  
  12.                   FrmCondition frmcon = new FrmCondition(path);  
  13.                   DialogResult = frmcon.ShowDialog();  
  14.                   if (DialogResult != DialogResult.OK)  
  15.                   {  
  16.                       throw new InstallException("用户取消安装!");  
  17.                   }  
  18.               }  
  19.               catch  
  20.               {  
  21.                   throw new InstallException("安装失败!");  
  22.               }  
  23.   
  24.               try  
  25.               {  
  26.                   //开启sqlbrower服务,因为SqlServer默认状态下是关闭的   
  27.                   WindowsService service = new WindowsService("SQLBrowser");  
  28.                   service.StartService();  
  29.               }  
  30.               catch { }  
  31.   
  32.               //数据库配置 界面   
  33.               Form1 dbFrom = new Form1();  
  34.               DialogResult = dbFrom.ShowDialog();  
  35.               if (DialogResult != DialogResult.OK)  
  36.               {  
  37.                   throw new InstallException("用户取消安装!");  
  38.               }  
  39.   
  40.               CreateMydb();  
  41.   
  42.   
  43.           }  
  44.           catch (Exception ex)  
  45.           {  
  46.   
  47.               throw new InstallException(ex.Message);  
  48.   
  49.           }  
  50.       }  
  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);
  
            }
        }


  1. private void CreateMydb()  
  2.    {  
  3.        string path = Context.Parameters["TARGETDIR"];  
  4.        string servername = _serverName; //服务器名字   
  5.        string dbname = _dbName;  //数据库名字   
  6.        string user = _userName; //用户名, 如‘sa’   
  7.        string pwd = _password; //相对应密码   
  8.        string Currentpath = System.IO.Directory.GetCurrentDirectory();  
  9.        string strSql = "server=" + servername + ";uid=" + user + ";pwd=" + pwd + ";database=master";//连接数据库字符串   
  10.        string strMdf = dbname + ".mdf";//MDF文件路径   
  11.        string strLdf = dbname + "_log.ldf";//LDF文件路径   
  12.        Sqldb mydb = new Sqldb();  
  13.   
  14.        System.Environment.CurrentDirectory = path;  
  15.        try  
  16.        {  
  17.            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine;  
  18.            Microsoft.Win32.RegistryKey software =  
  19.                        key.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Lsa"true); software.SetValue("forceguest", 0);  
  20.        }  
  21.        catch { }             
  22.          
  23.        mydb.CreateDataBase(strSql, dbname, strMdf, strLdf, path);//开始创建数据库   
  24.        System.Environment.CurrentDirectory = Currentpath;  
  25.    }  
     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,现将文件设置成可读
  1. class Sqldb  
  2.     {  
  3.         public void CreateDataBase(string strSql, string DataName, string strMdf, string strLdf, string path)  
  4.         {  
  5.             SqlConnection myConn = new SqlConnection(strSql);  
  6.             String str = null;  
  7.             SqlCommand myCommand;  
  8.             try  
  9.             {  
  10.                 SetChmod(strMdf);  
  11.                 SetChmod(strLdf);  
  12.                 str = " EXEC sp_attach_db @dbname='" + DataName + "',@filename1='" +path+ strMdf + "',@filename2='" + path + strLdf + "'";  
  13.                 myCommand = new SqlCommand(str, myConn);  
  14.                 myConn.Open();  
  15.                 myCommand.ExecuteNonQuery();  
  16.                 MessageBox.Show("数据库安装成功!点击确定继续");//需Using System.Windows.Forms   
  17.             }  
  18.             catch (Exception e)  
  19.             {  
  20.                 try  
  21.                 {  
  22.                     if (e.Message.IndexOf("已存在") > 0)  
  23.                     {  
  24.                         if (myConn.State == System.Data.ConnectionState.Open)  
  25.                         {  
  26.                             myConn.Close();  
  27.                         }  
  28.                         MyFile file = new MyFile();  
  29.                         string newMdf = strMdf + ".bak";  
  30.                         string newLdf = strLdf + ".bak";  
  31.                         file.CopyFile(strMdf, newMdf);  
  32.                         file.CopyFile(strLdf, newLdf);  
  33.   
  34.                         str = " EXEC sp_dbremove @dbname='" + DataName + "'";  
  35.                         myCommand = new SqlCommand(str, myConn);  
  36.                         myConn.Open();  
  37.                         myCommand.ExecuteNonQuery();  
  38.   
  39.                         file.MoveFile(newMdf, strMdf);  
  40.                         file.MoveFile(newLdf, strLdf);  
  41.   
  42.                         str = " EXEC sp_attach_db @dbname='" + DataName + "',@filename1='" + strMdf + "',@filename2='" + strLdf + "'";  
  43.                         myCommand = new SqlCommand(str, myConn);  
  44.                         //myConn.Open();   
  45.                         myCommand.ExecuteNonQuery();  
  46.                         MessageBox.Show("数据库安装成功!点击确定继续");  
  47.                     }  
  48.                 }  
  49.                 catch (Exception ex)  
  50.                 {  
  51.                     MessageBox.Show("数据库安装失败!" + ex.Message + "\n\n" + "您可以手动附加数据");  
  52.                     System.Diagnostics.Process.Start(path);//打开安装目录   
  53.                 }  
  54.   
  55.             }  
  56.             finally  
  57.             {  
  58.                 try  
  59.                 {  
  60.                     myConn.Close();  
  61.                 }  
  62.                 catch { }  
  63.             }  
  64.         }  
  65.   
  66.   
  67.         public void SetChmod(string filename)  
  68.         {  
  69.             string path = @filename;  
  70.             FileInfo fi = new FileInfo(path);  
  71.   
  72.             System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();  
  73.             fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));  
  74.             fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));  
  75.             fi.SetAccessControl(fileSecurity);  
  76.         }  
  77.   
  78.         public void RemoveDB(string strSql, string DataName, string strMdf, string strLdf, string path)  
  79.         {  
  80.             try  
  81.             {  
  82.                 SqlConnection myConn = new SqlConnection(strSql);  
  83.                 String str = null;  
  84.                 SqlCommand myCommand;  
  85.   
  86.                 myConn.Open();  
  87.                 str = " EXEC sp_dbremove @dbname='" + DataName + "'";  
  88.                 myCommand = new SqlCommand(str, myConn);  
  89.                 myCommand.ExecuteNonQuery();  
  90.                 myConn.Close();  
  91.             }  
  92.             catch { }  
  93.         }  
  94.     }  
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 { }
        }
    }

再在项目中添加安装项目



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


我的整个安装项目览图:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值