CREATE DATABASE (ADO.NET and C#)

Create a SQL Server Database Programmatically

You need to create a SQL Server database programmatically by using ADO.NET and C#. Here is a quick recipe how to do that.
using System;
using System.Data.SqlClient;

SqlConnection localConn = new SqlConnection ("(local); Integrated security=SSPI; database=master");
string SQLCommand = "CREATE DATABASE TestDb";

SqlCommand DbCreate = new SqlCommand(SQLCommand, localConn);
try
{
  localConn.Open();
  DbCreate.ExecuteNonQuery();
  Console.WriteLine("DataBase is Created Successfully");
}
catch (System.Exception ex)
{
  Console.WriteLine(ex.ToString());
}
finally
{
  if (localConn.State == ConnectionState.Open)
  {
    myConn.Close();
  }
}
This code creates a database similar to the SQL Server Model database and places its files to the default location. If you want to create a database with custom properties, please check out MSDN.

Comments

Popular posts from this blog

CREATE DATABASE (SMO)

Enable JSON serialization in your Visual Studio 2010 project

jQuery | remove inline style