.netsql-serverwindows-mobilecompact-database

Programmatically create MS SQL Compact database file on a desktop


Is it possible to create an SDF database file for MS SQL Server Compact on a desktop.?

I want to craete a desktop application which can create an SDF database file for copying it to a Windows Mobile device.

Is it possible and how?

thanks


Solution

  • Yes, this is possible. to quote from the MSDN page on SqlCeEngine.CreateDatabase:

    if (File.Exists("Test.sdf"))
    File.Delete("Test.sdf");
    
    string connStr = "Data Source = Test.sdf; Password = <password>;";
    
    SqlCeEngine engine = new SqlCeEngine(connStr);
    engine.CreateDatabase();
    engine.Dispose();
    SqlCeConnection conn = null;
    
    try 
    {
       conn = new SqlCeConnection(connStr);
       conn.Open();
    
       SqlCeCommand cmd = conn.CreateCommand();
       cmd.CommandText = "CREATE TABLE myTable (col1 int, col2 ntext)";
       cmd.ExecuteNonQuery();
    }
    
    catch {}
    
    finally 
    {
       conn.Close();
    }
    

    After this, you can just copy Test.sdf onto the mobile device.

    Hope this helps.