Pergunta

I have to connect my code to the access database but mainly, have to provide clear exception if that database file is not located in given location (like file not found). For this code :

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

I want to display message if test database is not present there. What can I do ? please suggest. thank you

Foi útil?

Solução

I think you can use the static method File.Exists:

if(!File.Exists("Z:\\test.accdb"))
    throw new FileNotFoundException();

Outras dicas

    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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top