且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建数据库文件(.sdf)如果不存在?

更新时间:2022-12-05 22:34:54

第二种方法更明智,因为如果程序依赖于要删除的数据库,则它是有用的。 / p>

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