创建数据库文件(.sdf)如果不存在? [英] Create database file (.sdf) if doesn't exists?

查看:106
本文介绍了创建数据库文件(.sdf)如果不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道有关此问题的一些做法;

Just wondering about some practice about this;

我用本地数据库(SQL CE)(dB.sdf文件)制作了一个简单的可视C#程序。

I have made a simple visual C# program with local database (SQL CE) (dB.sdf file).

比方说,用户删除了dB.sdf文件并尝试打开exe程序-没有任何反应(exe文件开始但再次关闭)。

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?

推荐答案

第二种方法更明智,因为如果程序依赖于要删除的数据库,则它是有用的。 / 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(); 
}
} 

这篇关于创建数据库文件(.sdf)如果不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆