Install SQL Server with c#
Yeah, this time this topic is in english.
Microsoft create instructions to create an installer of a database using VB, but there is no documentation related to c#.
http://msdn.microsoft.com/en-us/library/49b92ztk(v=VS.90).aspx
To download the code click here
This sample is using custom actions :
namespace ClassLibrary1
{
[RunInstaller(true)]
public partial class crearBD : Installer
{
public crearBD()
{
InitializeComponent();
}
private string GetSql(string Name)
{
try
{
Assembly asm = Assembly.GetExecutingAssembly();
Stream strm = asm.GetManifestResourceStream(asm.GetName().Name + "." + Name);
StreamReader reader = new StreamReader(strm, System.Text.Encoding.Default);
// System.Text.Encoding.ASCII;
return reader.ReadToEnd();
}
catch (Exception ex)
{
Console.Write("In GetSql:" + ex.Message);
throw ex;
}
}
private void ExecuteSql(string DataBaseName, string Sql)
{
//string ConnectionString = ConfigurationManager.ConnectionStrings["masterConnectionString"].ToString();
string ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=True";
SqlConnection sqlConnection1 = new SqlConnection(ConnectionString);
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql, sqlConnection1);
Command.Connection.Open();
Command.Connection.ChangeDatabase(DataBaseName);
try
{
Command.ExecuteNonQuery();
}
finally
{
Command.Connection.Close();
}
}
protected void AddDBTable(string strDBName)
{
try
{
ExecuteSql("master", "CREATE DATABASE " + strDBName);
ExecuteSql(strDBName, GetSql("script.sql"));
}
catch (Exception ex)
{
Console.WriteLine("In exception handler:" + ex.Message);
}
}
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
//Debugger.Break();
//AddDBTable("Juanito");
AddDBTable(this.Context.Parameters["dbname"]);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
File.Delete(@"c:\readme.txt");
}
}
}
Buen artículo, gracias por publicarlo!
ResponderEliminar¿Sabras cómo automatizar la instalación del Sql Server 2008 Express R2?
Saludos
Instalar SQL Server o una base de datos ?. Si es BD es lo mismo. Si es instalar todo el SQL Server, debes ver la instalación desatendida o unattended installation.
ResponderEliminar