Create SQLCE database programmatically

KMC picture KMC · Jun 1, 2011 · Viewed 22.8k times · Source

[EDITED - with answer]

Following is my code to create SQL CE database programmatically:

/* get the Path */
var directoryName = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var fileName = System.IO.Path.Combine(directoryName, "Foo2Database.sdf");

/* check if exists */
if (File.Exists(fileName))
    File.Delete(fileName);

string connStr = @"Data Source = " + fileName;

/* create Database */
SqlCeEngine engine = new SqlCeEngine(connStr);
engine.CreateDatabase();

/* create table and columns */
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
    using (SqlCeCommand cmd = new SqlCeCommand(@"CREATE TABLE FooTable (Foo_ID int, FooData NVARCHAR(200))", conn))
    {
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            conn.Close();
        }

    }
}

Answer

midhunhk picture midhunhk · Jun 1, 2011

I have worked with SQLCE 3.1 and SharpDevelop, Try this code and see if this is what you want:

string connStr = "Data Source = FooDatabase.sdf; Password = SomePassword";

if (File.Exists("FooDatabase.sdf")) 
    File.Delete("FooDatabase.sdf");  

SqlCeEngine engine = new SqlCeEngine(connStr); 
engine.CreateDatabase();

SqlCeConnection conn = null;


try 
{
    conn = new SqlCeConnection(connStr);
    conn.Open();

    SqlCeCommand cmd = conn.CreateCommand();
    cmd.CommandText = "CREATE TABLE FooTable(col1 int, col2 ntext)";
    cmd.ExecuteNonQuery();
}
catch 
{

}
finally 
{
    conn.Close();
}

Note that the database is just a file, so you can check if the database exists by looking if the file exists, also you can delete the database by deleting the file. Hope this helps.