How can I with \"code\" create a new .mdf/.sdf database?
I\'ve tried this: http://support.microsoft.com/kb/307283
All it does is fail on the ConnectionString
public static void CreateSqlDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new System.Data.SqlClient.SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
}
}
Change Catalog=tempdb
to Catalog=master
, its good worked
Sample use:
var filename = System.IO.Path.Combine("D:\\", "testdb.mdf");
if (!System.IO.File.Exists(filename))
{
CreateSqlDatabase(filename);
}
I suppose the problem is in the ConnectionString. It should point to the valid instance of the master db (as in the article you refer to). Make sure it is correct, and it should work.
If you need to create a database from scratch programmatically i normal go into the SQL Server Management Studio and create it through the gui in a first step. But instead of clicking on the OK button in the bottom right, i click on the Script button in the top toolbar. This will give me a complete sql script for creating the database i'd like to have. Then i can alter the script and change the parts i'd like dynamically.
Use a connectionString with InitialCatalog = master
. Since only master has default access to create a database.
Make sure you have a valid connection string.
The database/catalog that you need must be set to a valid database, usually this can be the "master" which is always available and since you will be using master to create a database.
Create .sdf database
using System.Data.SqlServerCe;
using System.IO;
string folderPath="D:\\Compact_DB"
string connectionString;
string fileName =folderPath+"\\School.sdf";
string password = "12345";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine obj_ceEngine = new SqlCeEngine(connectionString);
obj_ceEngine.CreateDatabase();