데이터 베이스 MySQL 튜토리얼 部署安装时写入SQLSERVER和Web.config

部署安装时写入SQLSERVER和Web.config

Jun 07, 2016 pm 03:51 PM
sqlserver 쓰다 설치하다 배포

在.NET平台下,部署 Web 解决方案是比较方便的。我们可以利用Visual Studio.NET 2003添加一个WEB安装项目,在部署的文件系统编辑器中添加项目的主输出和内容文件,非常简易地完成安装程序的制作。 但是,这样制作的安装程序,只是将Web页和ASP.NET程序编译的

在.NET平台下,部署 Web 解决方案是比较方便的。我们可以利用Visual Studio.NET 2003添加一个WEB安装项目,在部署的“文件系统编辑器”中添加项目的主输出和内容文件,非常简易地完成安装程序的制作。

但是,这样制作的安装程序,只是将Web页和ASP.NET程序编译的DLL文件安装到目标机器的IIS目录,对于一般的应用程序是可以的(比如用Access数据库,可以一起打包到安装程序中);如果数据库是SQL SERVER,需要在部署的时候一并安装数据库,安装程序的制作就会复杂一些,需要我们自定义安装程序类。在安装程序类中执行SQL脚本并将连接字符串写入Web.config。

l 安装数据库

微软MSDN上介绍过在部署应用程序的时候建立数据库。如:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxwlkWalkthroughUsingCustomActionToCreateDatabaseDuringInstallation.asp

这种方法是创建一个安装程序类,在安装程序类中调用ADO.NET执行SQL 语句(SQL语句放在一个文本文件中)来创建数据库。

 

但是,这种方法有一个问题,如果用SQL Server2000生成了所有建表、视图、存储过程的一个脚本文件,用ADO.NET来执行这个脚本文件,就会因为脚本中有许多“GO”语句而出现错误。当然,我们可以把“GO”替换成换行符,利用ADO.NET一条条执行SQL 语句。很显然,这样的效率比较低。

 

最好的办法是调用osql执行脚本。(或者创建一个数据库项目的cmd文件,而cmd文件建立数据库的时候也是调用的osql)。

using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Xml;

namespace DBCustomAction
{
///


/// DBCustomAction 的摘要说明。
///

[RunInstaller(true)]
public class DBCustomAction : System.Configuration.Install.Installer
{
///
///@author:overred
///

private System.ComponentModel.Container components = null;

public DBCustomAction()
{
// 该调用是设计器所必需的。
InitializeComponent();

// TODO: 在 InitializeComponent 调用后添加任何初始化
}

///


/// 清理所有正在使用的资源。
///

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


#region 组件设计器生成的代码
///


/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///

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

#region custom setup

 

private void ExecuteSql(string connString,string DatabaseName,string sql)
{
SqlConnection conn=new SqlConnection(connString);
SqlCommand cmd=new SqlCommand(sql,conn);
conn.Open();
cmd.Connection.ChangeDatabase(DatabaseName);
try
{
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
StreamWriter w=new StreamWriter(@"e://log.txt",true);
w.WriteLine("===in ExecuteSql======");
w.WriteLine(e.ToString());
w.Close();
}
finally
{
conn.Close();
}
}

public override void Install(IDictionary stateSaver)
{
createDB();
updateConfig();
}

private void createDB()
{
try
{
string connString=string.Format("server={0};user id={1};password={2}",this.Context.Parameters["server"],this.Context.Parameters["user"],this.Context.Parameters["pwd"]);

//根据输入的数据库名称建立数据库
ExecuteSql(connString,"master","create database " this.Context.Parameters["dbname"]);

//调用osql执行脚本
string cmd=string.Format(" -S{0} -U{1} -P{2} -d{3} -i{4}db.sql",this.Context.Parameters["server"],this.Context.Parameters["user"],this.Context.Parameters["pwd"],this.Context.Parameters["dbname"],this.Context.Parameters["targetdir"]);
System.Diagnostics.Process sqlProcess=new Process();
sqlProcess.StartInfo.FileName="osql.exe";
sqlProcess.StartInfo.Arguments=cmd;
sqlProcess.StartInfo.WindowStyle=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)
{
StreamWriter w=new StreamWriter(@"e:/log.txt",true);
w.WriteLine("===in Install======");
w.WriteLine(e.ToString());
w.Close();
}
}

private void updateConfig()
{
try
{
//将连接字符串写入Web.config
System.IO.FileInfo fileInfo=new FileInfo(string.Format("{0}web.config",this.Context.Parameters["targetdir"]));

if(!fileInfo.Exists)
throw new InstallException("can't find the web.config");

XmlDocument doc=new XmlDocument();
doc.Load(fileInfo.FullName);
bool foundIt=false;

string connString=string.Format("server={0};database={1};user id={2};password={3}",this.Context.Parameters["server"],this.Context.Parameters["dbname"],this.Context.Parameters["user"],this.Context.Parameters["pwd"]);

string enCS=SecurityHelper.EncryptDBConnectionString(connString);

XmlNode no=doc.SelectSingleNode("//appSettings/add[@key='connString']");
if(no!=null)
{
no.Attributes.GetNamedItem("value").Value=enCS;
foundIt=true;
}

if(!foundIt)
throw new InstallException("can't find the connString setting ");
doc.Save(fileInfo.FullName);
}
catch(Exception e)
{
StreamWriter w=new StreamWriter(@"e:/log.txt",true);
w.WriteLine("===in updata connstring=tjtj=====");
w.WriteLine(e.ToString());
w.WriteLine(e.StackTrace);
w.Close();
}
}

#endregion
}
}

 
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

sqlserver 데이터베이스에 이름이 지정된 개체가 이미 존재하는 문제를 해결하는 방법 sqlserver 데이터베이스에 이름이 지정된 개체가 이미 존재하는 문제를 해결하는 방법 Apr 05, 2024 pm 09:42 PM

sqlserver 데이터베이스에 이름이 지정된 개체가 이미 존재하는 문제를 해결하는 방법

mdf 파일을 sqlserver로 가져오는 방법 mdf 파일을 sqlserver로 가져오는 방법 Apr 08, 2024 am 11:41 AM

mdf 파일을 sqlserver로 가져오는 방법

sqlserver 서비스를 시작할 수 없는 경우 수행할 작업 sqlserver 서비스를 시작할 수 없는 경우 수행할 작업 Apr 05, 2024 pm 10:00 PM

sqlserver 서비스를 시작할 수 없는 경우 수행할 작업

sqlserver 데이터베이스는 어디에 있나요? sqlserver 데이터베이스는 어디에 있나요? Apr 05, 2024 pm 08:21 PM

sqlserver 데이터베이스는 어디에 있나요?

sqlserver에서 실수로 삭제한 데이터베이스를 복구하는 방법 sqlserver에서 실수로 삭제한 데이터베이스를 복구하는 방법 Apr 05, 2024 pm 10:39 PM

sqlserver에서 실수로 삭제한 데이터베이스를 복구하는 방법

sqlserver 포트번호 확인하는 방법 sqlserver 포트번호 확인하는 방법 Apr 05, 2024 pm 09:57 PM

sqlserver 포트번호 확인하는 방법

설치에 실패하면 sqlserver를 삭제하는 방법은 무엇입니까? 설치에 실패하면 sqlserver를 삭제하는 방법은 무엇입니까? Apr 05, 2024 pm 11:27 PM

설치에 실패하면 sqlserver를 삭제하는 방법은 무엇입니까?

sqlserver의 영어 설치를 중국어로 변경하는 방법 sqlserver의 영어 설치를 중국어로 변경하는 방법 Apr 05, 2024 pm 10:21 PM

sqlserver의 영어 설치를 중국어로 변경하는 방법

See all articles