Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
user1281991 Avatar asked Feb 20 '23 23:02

user1281991


1 Answers

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(); 
}
} 
like image 92
Coder Avatar answered Mar 04 '23 15:03

Coder