2011-01-25 13 views

答えて

7

は、単純に次のコードを実行し、それは新しいものを作成します。

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 
} 

表がすでに存在する場合、これらのエラーコードが返される - すべてのためcheck hereを。

12

特定のテーブルをチェックするためにテーブル名を反復することができます。テーブル名を取得するには、以下のコードを参照してください。

 string connectionstring = "Your connection string"; 
     string[] restrictionValues = new string[4]{null,null,null,"TABLE"}; 
     OleDbConnection oleDbCon = new OleDbConnection(connectionString); 
     List<string> tableNames = new List<string>(); 

     try 
     { 
      oleDbCon.Open(); 
      DataTable schemaInformation = oleDbCon.GetSchema("Tables", restrictionValues); 

      foreach (DataRow row in schemaInformation.Rows) 
      { 
       tableNames.Add(row.ItemArray[2].ToString()); 
      } 
     } 
     finally 
     { 
      oleDbCon.Close(); 
     }   
+0

1、です。 'catch {throw; } '、しかし:それはNOOPです。 – Heinzi

1

完全性期すために、私はしばらくは戻って私がTableExists() function within Accessをアップコーディングの4種類の方法を掲示することを指摘します。 MSysObjectsでSQL SELECTを実行するバージョンは外部からアクセスできますが、一部のコンテキストでは、Jet/ACEシステムテーブルへのアクセスが許可されていないため、セキュリティエラーが発生する可能性があります。

8

表は、あなたがこのようたDbConnectionを拡張することができますが存在するかどうかを確認するには、次の

public static class DbConnectionExtensions 
{ 
    public static bool TableExists(this DbConnection conn, string table) 
    { 
     conn.open(); 
     var exists = conn.GetSchema("Tables", new string[4] { null, null, table, "TABLE" }).Rows.Count > 0; 
     conn.close(); 
     return exists; 
    } 
} 

その後、あなたはOleDbConnectionオブジェクト、SQLiteConnectionまたはSqlConnectionオブジェクトなどの任意の派生クラスでTableExistsを呼び出すことができます。

1

これを行う簡単な方法は、単にエラーをキャッチするよりもエレガント

public bool CheckTableExistance(string TableName) 
    { 
     // Variable to return that defines if the table exists or not. 
     bool TableExists = false; 

     // Try the database logic 
     try 
     { 
      // Make the Database Connection 
      ConnectAt(); 

      // Get the datatable information 
      DataTable dt = _cnn.GetSchema("Tables"); 

      // Loop throw the rows in the datatable 
      foreach (DataRow row in dt.Rows) 
      { 
       // If we have a table name match, make our return true 
       // and break the looop 
       if (row.ItemArray[2].ToString() == TableName) 
       { 
        TableExists = true; 
        break; 
       } 
      } 

      //close database connections! 
      Disconnect(); 
      return TableExists; 
     } 
     catch (Exception e) 
     { 
      // Handle your ERRORS! 
      return false; 
     } 
    } 
関連する問題