我需要通过代码修改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,语法相似 - 您明白了。)
ADO.NET是否有像ADOX类似的东西,还是我坚持使用DDL语句或引用旧的DAO / ADOX库?
答案 0 :(得分:1)
我用直接的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;
}