前几天有人问:如何在使用 C# 或者 VB.NET 读写 Access 数据库的标题信息?Access 数据库的有些信息不能通过 ADO.NET 来读取的,需要使用 DAO 来进行读写,这些属性包括:
?Caption
?ColumnHidden
?ColumnOrder
?ColumnWidth
?
DecimalPlaces
?Description
?Format
?InputMask
等等,使用 DAO 可以采用下面的方法进行读写,附上完整源代码:
/// 需要添加引用 Microsoft DAO 3.6 Object Library
/// 在VS 2008和Access 2003下测试通过
const int dbUseJet = 2 ;
const int dbPropNotFound = 3270 ;
const dao.DataTypeEnum dbText = dao.DataTypeEnum.dbText;
String dbName = @" E:\WebSite1\MengXianhui\db3.mdb " ;
dao.Workspace DAOWorkspace;
dao.Database DAODatabase;
dao.DBEngine DAODBEngine = new dao.DBEngine();
// 创建一个工作区
DAOWorkspace = DAODBEngine.CreateWorkspace( " WorkSpace " , " Admin " , "" , dbUseJet);
// 打开数据库
DAODatabase = DAOWorkspace.OpenDatabase(dbName, false , false , null );
dao.TableDef DAOTable;
dao.Field DAOField;
// 表对象
DAOTable = DAODatabase.TableDefs[ " Table1 " ];
DAOField = DAOTable.Fields[ " BirthDay " ];
// 读取 UserName 字段的 “标题”属性,如果标题没有设置,则会抛出异常。
// 如果标题不存在,我们就添加一个标题
String CaptionText;
try
{
CaptionText = DAOField.Properties[ " Caption " ].Value.ToString();
}
catch
{
if (dbPropNotFound == DAODBEngine.Errors[ 0 ].Number)
{
// 此时属性不存在,添加一个属性
dao.Property dbProperty = DAOField.CreateProperty( " Caption " , dbText, " 出生日期字段标题 " , false );
DAOField.Properties.Append(dbProperty);
DAOField.Properties.Refresh();
CaptionText = DAOField.Properties[ " Caption " ].Value.ToString();
}
else
{
CaptionText = " 无此标题,并且未能创建标题。 " ;
}
}
finally
{
DAODatabase.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(DAOField);
System.Runtime.InteropServices.Marshal.ReleaseComObject(DAOTable);
System.Runtime.InteropServices.Marshal.ReleaseComObject(DAOWorkspace);
System.Runtime.InteropServices.Marshal.ReleaseComObject(DAODBEngine);
System.Runtime.InteropServices.Marshal.ReleaseComObject(DAODatabase);
DAOField = null ;
DAOTable = null ;
DAOWorkspace = null ;
DAOWorkspace = null ;
DAODatabase = null ;
GC.WaitForPendingFinalizers();
GC.Collect();
}
MessageBox.Show( " BirthDay 字段的标题是: " + CaptionText);
VB.NET写法类似,网上也有C#转换成VB.NET的工具,如果实在转换不成,可以继续找我。