Creating a SQLEXPRESS database file from code
programming, sqlexpress, tech October 20th, 2008Creating a SQLEXPRESS database file from code was a bit tricky to figure out. If you’re using it as an embedded database engine, like SQLite, one of the things I was looking for was the ability to “get code and run” a project locally. The internet was especially unhelpful because everything was coming back with descriptions of using Visual Studio or SQL Management Consoles, or with topics about how to handle errors that happen creating the aspnetdb.mdf file.
So to cut right to the chase, here’s how you do it:
public static void CreateSqlExpressDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=tempdb;"+
"Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
"CREATE DATABASE " + databaseName +
" ON PRIMARY (NAME=" + databaseName +
", FILENAME='" + filename + "')";
command.ExecuteNonQuery();
command.CommandText =
"EXEC sp_detach_db '" + databaseName + "', 'true'";
command.ExecuteNonQuery();
}
}
}
Pretty simple in the end. Creates a connection to sqlexpress for the purpose of creating the database in a specific location, then removes it from the sql server instance’s knowledge. The use of tempdb in the connection string is important when this code is run from a context that has very low permissions. While running the app in the webdev.webserver (I try not to develop as a local admin) a connection to the default catalog ‘master’ was denied.
In theory the databaseName doesn’t matter, but it does appear several times in the mdf file.
Now if you’re using an embedded database with a connection string like Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\MyData.mdf;Integrated Security=True;User Instance=True; you can create it when your global application start with something like this:
var appData = (string)AppDomain.CurrentDomain.GetData("DataDirectory");
var filename = System.IO.Path.Combine(appData, "MyData.mdf");
if (!System.IO.File.Exists(filename))
CreateSqlExpressDatabase(filename);
Followed by a call to ActiveRecordStarter.UpdateSchema(); of course!
October 21st, 2008 at 7:34 pm
I am looking for some idea and stumble upon your posting :) decide to wish you Thanks. Eugene
October 21st, 2008 at 10:12 pm
I’m glad you found it. I was hoping there were enough keywords to catch search traffic because like I said I couldn’t find the answer anywhere.
October 26th, 2008 at 9:05 pm
Eugene is stumbling around the internet. :)
http://www.google.com/search?q=I+am+looking+for+some+idea+and+stumble+upon+your+posting+:)+decide+to+wish+you+Thanks.+Eugene
I had the same strange comment on my blog the other day. Strange bot.
October 27th, 2008 at 11:48 pm
Well how do you like that! Dang bots. I’m usually more suspicious if the name would link to skin care products or ways to save money on insurance.
It might be a two-phase bot because some blogs will white-list a person… After the first comment is approved others can go through without moderation.
November 16th, 2008 at 10:35 pm
[...] started searching for how to create a file-based SQL Express database using code, and came up with Louis DeJardin’s great blog post that walked me right though it. After I had that, it was a simple matter of whipping up the [...]