0

我必须将我的代码连接到访问数据库,但主要是,如果该数据库文件不在给定位置(如找不到文件),则必须提供明确的异常。对于此代码:

string connStr =( @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;             

OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";

conn1.Open();
cmd.ExecuteNonQuery();

如果那里不存在测试数据库,我想显示消息。我能做些什么 ?请建议。谢谢你

4

2 回答 2

2

我认为您可以使用静态方法File.Exists

if(!File.Exists("Z:\\test.accdb"))
    throw new FileNotFoundException();
于 2013-09-07T13:24:26.070 回答
1
    try
{
string connStr =( @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;             

OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";

conn1.Open();
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
 //print the message you want;
}
于 2013-09-07T13:24:38.717 回答