//执行SQL 语句
private void ExecuteSql(string conn,string DatabaseName,string Sql)
{
SqlConnection mySqlConnection = new SqlConnection(conn);
SqlCommand Command = new SqlCommand(Sql,mySqlConnection);
Command.Connection.Open();
Command.Connection.ChangeDatabase(DatabaseName);
try
{
Command.ExecuteNonQuery();
}
catch(Exception e)
{
throw new Exception(e.Message);
}
finally
{
Command.Connection.Close();
}
}

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",
this.Context.Parameters["server"],this.Context.Parameters["user"],this.Context.Parameters["pwd"]);

//根据输入的数据库名称建立数据库
ExecuteSql(connStr,"master","CREATE DATABASE " + this.Context.Parameters["dbname"]);
//调用osql执行脚本
System.Diagnostics.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",
this.Context.Parameters["user"],
this.Context.Parameters["pwd"],
this.Context.Parameters["dbname"],
this.Context.Parameters["targetdir"]);

sqlProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
sqlProcess.Start();
sqlProcess.WaitForExit();
//等待执行;
sqlProcess.Close();
//删除脚本

System.IO.FileInfo sqlFileInfo = new FileInfo(string.Format("{0}db.sql",this.Context.Parameters["targetdir"]));
if ( sqlFileInfo.Exists )
{
sqlFileInfo.Delete();
}
}
catch(Exception e)
{
throw new Exception(e.Message);
}

// ---------------------将连接字符串写入Web.config-----------------------------------
try
{

FileInfo FileInfo = new FileInfo(this.Context.Parameters["targetdir"] + @"\web.config");
if ( !FileInfo.Exists )
{
throw new InstallException("没有找到配置文件");
}
//实例化XML文档
System.Xml.XmlDocument Xmldocument = new System.Xml.XmlDocument();
Xmldocument.Load(FileInfo.FullName);
//查找到appSettings中的节点

bool FoundIt = false;
foreach( System.Xml.XmlNode Node in Xmldocument.DocumentElement["configuaration"]["appSettings"])
{
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",
this.Context.Parameters["server"],this.Context.Parameters["dbname"],this.Context.Parameters["user"],this.Context.Parameters["pwd"]); FoundIt = true;
}
}
}
if ( !FoundIt ) 
{
throw new InstallException("web.Config 文件没有包含connString连接字符串设置");
}
Xmldocument.Save(FileInfo.FullName);
}
catch ( Exception e ) 
{
throw new Exception(e.Message);
}
}