简体   繁体   中英

Check if OleDb database exists

I tried to look around but I failed to find anyone (even in SO) who explained how to check if an Access database exists or not using OleDb 12.0. I figured out how to create a database:

Catalog cat = new CatalogClass();
string cntPath = System.IO.Directory.GetCurrentDirectory();
string createStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + cntPath + "\\" + TB_LoginUsername.Text.ToLower() + "_LOG.accdb;";
cat.Create(createStr);
Table tbl = new Table();
tbl.Name = TB_LoginUsername.Text + "_SESSIONS";
tbl.Columns.Append("ID", DataTypeEnum.adGUID);
tbl.Columns.Append("Cycling", DataTypeEnum.adVarWChar, 25);
tbl.Columns.Append("Running", DataTypeEnum.adVarWChar, 25);
tbl.Columns.Append("Swimming", DataTypeEnum.adVarWChar, 25);
cat.Tables.Append(tbl);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(tbl);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.Tables);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);

But I don't understand how to check if one exists or not - could anyone guide me how to do this? I'm suspecting it's something to do with File.Exists() but I don't know how to use it.

Thanks!

Here's a working code to check if table exists:

try
{
        OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + frmMain.strFilePath + "\\ConfigStructure.mdb");
        myConnection.Open();
        OleDbCommand myCommand = new OleDbCommand();
        myCommand.Connection = myConnection;
        myCommand.CommandText = "CREATE TABLE <yourtable name>(<columns>)";
        myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();
}
catch(OleDbException e)
{  
    if(e.ErrorCode == 3010 || e.ErrorCode == 3012)
    // if error then table exist do processing as required
}

UPDATE

If you wanna check database exists or not: You can use DTO , get a list of Database names, check for the one you need, and react appropriately or you can open your ADO connection. If you get an error opening the connection that says “datasource not found an no default driver specified” (from ODBC) or “[LNA][Pervasive][ODBC Engine Interface][Data Record Manager]Cannot locate the named database you specified(Btrieve Error 2301)” (from OLEDB), then the database doesn't exist.

You can use DTO to create it if it doesn't exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM