2012-04-01 121 views
4

只是想知道一些這方面的做法;如果不存在,創建數據庫文件(.sdf)?

我用本地數據庫(SQL CE)(dB.sdf文件)製作了一個簡單的可視化C#程序。

比方說,用戶刪除dB.sdf文件,並嘗試打開exe程序 - 沒有任何反應(exe文件啓動,但再次關閉)。

這裏的典型做法是什麼?難道程序不會啓動,還是讓程序創建一個數據庫文件(如果它不存在的話)?

如果是後者,它是如何完成的?

問候

回答

7

第二種方法是更明智的你的程序是uselsess如果這要看被刪除數據庫。

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(); 
} 
} 
0
    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(); 
        } 
相關問題