您的位置:首页 > 数据库

c# 打包程序中自动附加安装SQL Server数据库

2015-01-16 14:56 176 查看
1、创建安装项目“Setup”安装项目
在“文件”菜单上指向“添加项目”,然后选择“新建项目”。
在“添加新项目”对话框中,选择“项目类型”窗格中的“安装和部署项目”,然后选择“模板”窗格中的“安装项目”。在“名称”框中键入 “setup”(其他名称也行,随个人意愿)。
单击“确定”关闭对话框。
项目被添加到解决方案资源管理器中,并且文件系统编辑器打开。
在“属性”窗口中,选择 ProductName 属性,并键入”xxxx系统”(你所做项目程序的名称)。

2、在安装项目中创建安装程序类(install.cs)。
在你项目的解决方案上右键,选择“添加”中的“新建项目”。然后选择“类库”,在名称中输入DbSetUp,位置选择你的项目程序所在目录。点“确定”关闭对话框。
在新项目“DbSetUp”上右键,选择“添加”中的“新建项”。然后选择Visual c#项目项中的“安装程序类”,点“添加”关闭对话框。
切换到代码视图,在install.cs文件中写入如下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Data.SqlClient;

namespace DBSetUp
{
[RunInstaller(true)]
public partial class Installer1 : Installer
{
public Installer1()
{
InitializeComponent();
}

private void CreateDataBase()
{
// 启动SQL服务, 预防装完之后服务未启动
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";

p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;

p.Start();
p.StandardInput.WriteLine("net start MSSQL$Rybx");//Rybx为客户端数据库实例名
p.StandardInput.WriteLine("exit");
p.StandardOutput.ReadToEnd();

// “server”:客户端数据库实例名, “user id”:Sa ,“password”:Sa的密码
string strSql = string.Format("server={0}; user id={1}; password={2}; Database=master", @"(local)/Rybx", "sa", "qjs");
//需要附加的数据库文件,我的设置是在项目程序的安装目录下的database文件夹下
string strMdf = this.Context.Parameters["targetdir"] + @"/database/RybxMis.mdf";
string strLdf = this.Context.Parameters["targetdir"] + @"/database/RybxMis.ldf";

string str;
SqlConnection myConn = new SqlConnection(strSql);
str = "EXEC sp_attach_db @dbname = N'RybxMis', @filename1 = N'" + strMdf + "',@filename2=N'" + strLdf + "'";
SqlCommand myCommand = new SqlCommand(str, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}

protected override void OnAfterInstall(System.Collections.IDictionary savedState)
{
base.OnAfterInstall(savedState);
try
{
CreateDataBase();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}

}
}


单击“生成”菜单下“生成解决方案”,生成install.dll安装类文件。
3、将“主程序”项目的输出添加到部署项目中
在你项目程序的安装项目(上面第一步创建的Setup)上右键,选择“视图”中的“文件系统”,在 “应用程序文件夹”上右键,选择“添加”中的“项目输出”,打开“添加项目输出组”对话框,在“项目”下拉表框中选择你的主安装程序类,如上面的“DbSetUp”。
从列表框中选择“主输出”组,然后单击“确定”关闭。
4、创建自定义安装对话框
如需要可在解决方案资源管理器中选择安装项目“Setup”项目,在“视图”菜单上指向“编辑器”,然后选择“用户界面”。在用户界面编辑器具中,选择“安装”下的“启动”节点。在“操作”菜单上,选择“添加对话框”。详细设置请参考msdn,这里不再详细说明。
5、建自定义操作
在安装项目“Setup”项目上右键,选择“视图”中的“自定义操作”。
在“自定义操作”中选择“安装”节点。单击右键“添加自定义操作”,在选择项目中的项中选择“应用程序文件夹”,选择“主输出来自DbSetUp(活动)”。
左键点击“主输出来自DbSetUp(活动)”,在“属性窗口”中选择“CustomActionData”属性并键入/targetdir="[TARGETDIR]/"。
/targetdir="[TARGETDIR]/" 是你项目程序的安装路径,设置此参数以便在install类中获得该路径。
在安装项目“Setup”项目上右键,单击“生成”,即可生成项目程序的安装程序,即SetUp.exe。在实际部署中最后需要用Orca MSI安装文件修改器修改设置SetUp.exe文件,详细请参照“将MSDE Sp3(注意是sp3)打包进.Net安装项目中(WinForm应用)”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: