Create Content Database programmatically
28/01/2014 15:00
string newDbName = "SP_Content_testSite1";
int warningSiteCollectionNumber = 0;
int maximumSiteCollectionsNumber = 1;
SPWebApplication webApp = site.WebApplication;
string dbserver = SPWebService.ContentService.DefaultDatabaseInstance.NormalizedDataSource;
//SPContentDatabase contentDatabase = null;
//if count of content databases with name 'newDbName' is > 0, then already exists
if (site.WebApplication.ContentDatabases.OfType<SPContentDatabase>().Count(db => db.Name.Equals(newDbName, StringComparison.InvariantCultureIgnoreCase)) > 0)
{
Console.WriteLine("Content DB uz existuje!!!");
Console.ReadLine();
}
else
{
Console.WriteLine("Creating...");
//ak nie vytvorim novu
SPContentDatabase contentDatabase = webApp.ContentDatabases.Add(
dbserver,
newDbName,
null,
null,
warningSiteCollectionNumber,
maximumSiteCollectionsNumber,
0);
Console.WriteLine("Updating...");
contentDatabase.Update();
webApp.Update();
Console.WriteLine("Done.");
Console.ReadLine();
}
//set your serverName, userName and Password
//this code had following error for me, so code above is working
//Cannot connect to database master at sql server <Servername>. The database might not exist, or the current user does not have permission to connect to it.
using (SPSite site = new SPSite("https://yourSiteUrl"))
{
string newDbName = "SP_Content_testSite";
int warningSiteCollectionNumber = 0;
int maximumSiteCollectionsNumber = 1;
SPWebApplication webApp = site.WebApplication;
SPContentDatabase contentDatabase = webApp.ContentDatabases.Add(
DatabaseServerName,
newDbName,
DatabaseAdminUserName,
DatabaseAdminUserPassword,
warningSiteCollectionNumber,
maximumSiteCollectionsNumber,
0);
contentDatabase.Update();
webApp.Update();
}