Search code examples
c#databasevisual-studio-2010sql-server-ce

Create database file (.sdf) if doesn't exists?


Just wondering about some practice about this;

I have made a simple visual C# program with local database (SQL CE) (dB.sdf file).

Let's say user deletes the dB.sdf file and try to open the exe program - nothing happens (the exe file starts but closes again).

What's the typically practice here? Is it that the program just won't start or is it to make the program create a database file if it doesn't exists?

If it is the latter, how is it done?


Solution

  • The second approach is more wise as your program is uselsess if it depends on database which gets deleted.

    string connStr = "Data Source = DBName.sdf; Password = DBPassword";  
    
    if (!File.Exists("DBName.sdf")){
    
    try  {     
    SqlCeEngine engine = new SqlCeEngine(connStr);  
    engine.CreateDatabase();  
    
    SqlCeConnection conn = new SqlCeConnection(connStr);     
    conn.Open();      
    
    SqlCeCommand cmd = conn.CreateCommand();     
    cmd.CommandText = "CREATE TABLE TableName(Col1 int, Col2 varchar(20))";     
    cmd.ExecuteNonQuery(); 
    
    } 
    catch (SQLException ex){
        // Log the exception
    } 
    finally  {     
    conn.Close(); 
    }
    }