Hei*_*nzi 5 c# database ado.net ms-access dao
我需要通过代码修改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 语句取得了相当大的成功。你是对的,语法需要一点谷歌搜索才能弄清楚,但我已经用这种方式处理本地数据库的更新有一段时间了。您是否遇到了特定更新的问题?基本上,我编写了一些辅助函数来检查表的结构并在需要时附加字段。
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2252 次 |
最近记录: |