ASP.NET安装和部署中数据库的问题
现我在ASP.NET部署数据库时出现这样一个问题..如果sql.txt中遇到有存储过程,安装程序将会出错误..提示错误:ExecuteNonQuery:CommandText 属性尚未初始化 然后数据确实在SQL中存在了..但里面没有内容,表一个都没有. 觉得代码需要改进,麻烦高手指点了(这段代码是网上找的,很多地方都有)
代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Data.SqlClient;
using System.Reflection;
namespace DBCustomAction
{
/// <summary>
/// DBCustomAction 的摘要说明。
/// </summary>
[RunInstaller(true)]
public class DBCustomAction : System.Configuration.Install.Installer
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private string strPass = "";
private string strUser = "";
private string strServer = "";
public DBCustomAction()
{
// 该调用是设计器所必需的。
InitializeComponent();
// TODO: 在 InitializeComponent 调用后添加任何初始化
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
public override void Install(System.Collections.IDictionary stateSaver)
{
//入口
strPass = this.Context.Parameters["strPass"];
strUser = this.Context.Parameters["strUser"];
strServer = this.Context.Parameters["strServer"];
AddDBTable("RequestSys");//RequestSys为数据库名称
}
protected void AddDBTable(string strDBName )
{
try
{
//Create the database.
ExecuteSql("master", "CREATE DATABASE " + strDBName);
// Create the tables.
ExecuteSql(strDBName, GetSql("sql.txt"));
}
catch(Exception ex)
{
throw ex;
}
}
private void ExecuteSql(string DatabaseName , string Sql)
{
SqlConnection conn = new SqlConnection("user id="+strUser+";password="+strPass+";database=master;server="+strServer) ;
SqlCommand Command = new SqlCommand(Sql,conn);
Command.Connection.Open();
Command.Connection.ChangeDatabase(DatabaseName);
try
{
Command.ExecuteNonQuery();
}
catch(Exception ex)
{
throw ex ;
}
finally
{
// Finally, blocks are a great way to ensure that the connection
Command.Connection.Close();
}
}
private string GetSql(string strName)
{
try
{
//' Get the current assembly.
Assembly Asm = Assembly.GetExecutingAssembly();
// Resources are named using a fully qualified name
Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + strName);
//Read the contents of the embedded file.
StreamReader reader= new StreamReader(strm);//,System.Text.Encoding.Unicode);
return reader.ReadToEnd();
}
catch
{
return null;
}
}