22

How can I create a database programmatically and what is the minimum information I need to do this?

Please no "SQL Server Management Object API " suggestions.

6 Answers 6

29

You can either use the SQL Server Management Object API (see task "creating, altering and removing databases"):

 var srv = new Server();
 var db = new Database(srv, "mydb");
 db.Create();

Information on how to get started is here. During SQL server installation you need to install the client SDK, the SMO assemblies are in C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies

Or if you don't want the dependency on these assemblies, you can also simply run DDL statements using ADO.Net (e.g. see this question):

using (var connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "CREATE DATABASE mydb";
    command.ExecuteNonQuery();
}  

Obviously you need a correct connection string: known sql server instance and a user with CREATE DATABASE permission.

7
  • I did this but I get login failed. What user should I choose?
    – Pascal
    Jan 26, 2012 at 7:55
  • 1
    You should use a user with the correct permissions. You can test this by connecting with the same credentials via SQL Management Studio and create the DB manually.
    – jeroenh
    Jan 26, 2012 at 8:01
  • It also helps to read the documentation. This is a junior level problem (login failed). At least try to understand the software you work with.
    – TomTom
    Jan 26, 2012 at 8:23
  • easy enough, go ahead and post your connection string. Do you have an SA user, maybe use that?
    – RandomUs1r
    Feb 21, 2013 at 23:15
  • 1
    Beware that the SMO Classes are not available in .net 4.0: connect.microsoft.com/SQLServer/feedback/details/643811/…
    – stefan.s
    Jan 19, 2016 at 14:21
8
Create database 'Databasename'
1
  • 5
    stupid of course this works, I just used a non-existant/fictive connection string to create the db :P
    – Pascal
    Jan 27, 2012 at 7:43
7

From the creators:

// your connection string
string connectionString = "Server=(local)\\netsdk;uid=sa;pwd=;database=master";

// your query:
var query = GetDbCreationQuery();

var conn = new SqlConnection(connectionString);
var command = new SqlCommand(query, conn);

try
{
    conn.Open();
    command.ExecuteNonQuery();
    MessageBox.Show("Database is created successfully", "MyProgram", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
finally
{
    if ((conn.State == ConnectionState.Open))
    {
        conn.Close();
    }
}

To create in default location with default settings, just:

static string GetDbCreationQuery()
{
    // your db name
    string dbName = "MyDatabase";

    // db creation query
    string query = "CREATE DATABASE " + dbName + ";";

    return query;
}

Or, to create it in a specific location:

static string GetDbCreationQuery()
{
    // your db name
    string dbName = "MyDatabase";

    // path to your db files:
    // ensure that the directory exists and you have read write permission.
    string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"), 
                       Path.Combine(Application.StartupPath, dbName + ".ldf") };

    // db creation query:
    // note that the data file and log file have different logical names
    string query = "CREATE DATABASE " + dbName +
        " ON PRIMARY" +
        " (NAME = " + dbName + "_data," +
        " FILENAME = '" + files[0] + "'," +
        " SIZE = 3MB," +
        " MAXSIZE = 10MB," +
        " FILEGROWTH = 10%)" +

        " LOG ON" +
        " (NAME = " + dbName + "_log," +
        " FILENAME = '" + files[1] + "'," +
        " SIZE = 1MB," +
        " MAXSIZE = 5MB," +
        " FILEGROWTH = 10%)" +
        ";";

    return query;
}

Even in case the execution fails, give it another try. The db files might have got created.

0

You need to open a connection to the server, i.e. you need a server and instance name.

You also need the proper access rights to create a database, so you might need some user name and password depending on the authentication settings on the server.

From the server name and authentication information you can construct a connection string and open a connection.

Then you can use the CREATE DATABASE SQL command (see here on MSDN). The only needed parameter for this command is a database name.

0

You need connection information: server, possibly instance, a user having create database rights on that server/instance and the corresponding password. Then you can use SMO for creating the database. Here is a small PowerShell example that you can very easily "translate" to C#, for example:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null

$s = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)

# Instantiate the database object and add the filegroups
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($s, $DatabaseName)
$primaryFG = New-Object Microsoft.SqlServer.Management.Smo.FileGroup($db, 'PRIMARY')
$db.FileGroups.Add($primaryFG)

# Create Data file
$syslogname = $DatabaseName + '_SysData'
$dbdsysfile = New-Object Microsoft.SqlServer.Management.Smo.DataFile($primaryFG, $syslogname)
$primaryFG.Files.Add($dbdsysfile)
$dbdsysfile.FileName = $s.MasterDBPath + '\' + $syslogname + '.mdf'
$dbdsysfile.Size = [double](5.0 * 1024.0)
$dbdsysfile.GrowthType = 'KB'
$dbdsysfile.Growth = 10000.0
$dbdsysfile.IsPrimaryFile = 'True'

# Create Log file
$loglogname = $DatabaseName + '_Log'
$dblfile = New-Object Microsoft.SqlServer.Management.Smo.LogFile($db, $loglogname)
$db.LogFiles.Add($dblfile)
$dblfile.FileName = $s.MasterDBLogPath + '\' + $loglogname + '.ldf'
$dblfile.Size = [double](10.0 * 1024.0)
$dblfile.GrowthType = 'KB'
$dblfile.Growth = 10000.0

# Create database with READ_COMMITTED_SNAPSHOT isolation level.
# Other options can be set on $db object before calling Create.
$db.IsReadCommittedSnapshotOn = $true

$db.RecoveryModel = [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple
$db.Create()
0

Assuming you have the rights to fire off a CREATE DATABASE statement you can do so as you would any other query.

I should stress that being able to do so requires quite high privileges on the server and this would be restricted to DBAs in QA and Production environments.

For that reason I would make sure that your connection uses Windows Integrated Security. That way when the appropriate DBA runs your application the app will function as requested.

Once you have created your database you will also need to fire off the T-SQL to create logins and create users. I'm taking it as obvious that CREATE TABLE/VIEW statements will be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.