Reputation: 773
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?
Upvotes: 4
Views: 9205
Reputation: 1391
string fileName = txtEditFolderPath.Text + "\\" + txtEditDatabaseName.Text + ".sdf";
if (File.Exists(fileName))
{
MessageBox.Show("Database with this name already existed at this location !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
string connectionString;
string password = "123";
connectionString = string.Format(
"DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine en = new SqlCeEngine(connectionString);
en.CreateDatabase();
}
Upvotes: 0
Reputation: 3956
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();
}
}
Upvotes: 8