[英]Is it possible to modify an MS Access database schema using ADO.NET?
我需要通過代碼修改MS Acess數據庫(.mdb)的模式 。
由於Jet Engine DDL語句(ALTER TABLE等)的文檔很少,我更喜歡使用某種對象庫,如DAO( myDatabase.TableDefs("myTable").Fields.Append(myNewField)
)或ADOX ( myCatalog.Tables("myTable").Columns.Append(myNewField)
)或SMO(僅適用於SQL Server,語法類似 - 你明白了)。
是否有像ADOX.NET類似的東西,或者我是否堅持使用DDL語句或引用舊的DAO / ADOX庫?
我用直接的ddl語句取得了不錯的成功。 你的權利語法需要一個微笑的googling來梳理,但我一直在用這種方式處理本地數據庫的更新。 您是否有特定的更新問題? 基本上我寫了一些輔助函數來檢查表的結構並在需要時附加字段。
public bool doesFieldExist(string table, string field)
{
bool ret = false;
try
{
if (!openRouteCon())
{
throw new Exception("Could not open Route DB");
}
DataTable tb = new DataTable();
string sql = "select top 1 * from " + table;
OleDbDataAdapter da = new OleDbDataAdapter(sql, routedbcon);
da.Fill(tb);
if (tb.Columns.IndexOf(field) > -1)
{
ret = true;
}
tb.Dispose();
}
catch (Exception ex)
{
log.Debug("Check for field:" + table + "." + field + ex.Message);
}
return ret;
}
public bool checkAndAddColumn(string t, string f, string typ, string def = null)
{
// Update RouteMeta if needed.
if (!doesFieldExist(t, f))
{
string sql;
if (def == null)
{
sql = String.Format("ALTER TABLE {0} ADD COLUMN {1} {2} ", t, f, typ);
}
else
{
sql = String.Format("ALTER TABLE {0} ADD COLUMN {1} {2} DEFAULT {3} ", t, f, typ, def);
}
try
{
if (openRouteCon())
{
OleDbCommand cmd = new OleDbCommand(sql, routedbcon);
cmd.ExecuteNonQuery();
string msg = "Modified :" + t + " added col " + f;
log.Info(msg);
if (def != null)
{
try
{
cmd.CommandText = String.Format("update {0} set {1} = {2}", t, f, def);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
log.Error("Could not update column to new default" + t + "-" + f + "-" + e.Message);
}
}
return true;
}
}
catch (Exception ex)
{
log.Error("Could not alter RouteDB:" + t + " adding col " + f + "-" + ex.Message);
}
}
else
{
return true;
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.