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

佐手、 提交于 2019-12-06 06:45:53

问题


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?


回答1:


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(); 
}
} 



回答2:


                    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();
                     }


来源:https://stackoverflow.com/questions/9964412/create-database-file-sdf-if-doesnt-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!