[英]How to find Identity column name of a table in MS-Access database using c# Code?
我想使用c#代码找出MS-Access数据库中表的标识列名称。
请帮我。
这段代码是我的o / r-mapper的一部分
private string RetrieveAutoNumberColumn(OleDbConnection cnn, TableSchema tableSchema)
{
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + tableSchema.TableName + "] WHERE False", cnn);
DataTable dtSchema = adapter.FillSchema(new DataTable(), SchemaType.Source);
if (dtSchema == null) {
throw new UnimatrixMappingException("Table \"" + tableSchema.TableName + "\" not found. Connection = " + this._connectString);
}
string columnName = null;
for (int i = 0; i < dtSchema.Columns.Count; i++) {
if (dtSchema.Columns[i].AutoIncrement) {
columnName = dtSchema.Columns[i].ColumnName;
break;
}
}
return columnName;
}
像这样创建连接
var cnn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\Data\MyDatabase.mdb\";OLE DB Services=-1");
您可以像这样检索主键(不一定与“自动编号”列相同)
private static void RetrievePrimaryKeyInfo(OleDbConnection cnn, TableSchema tableSchema, string[] restrictions)
{
using (DataTable dtPrimaryKeys = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, restrictions)) {
foreach (DataRow row in dtPrimaryKeys.Rows) {
string columnName = (string)row["COLUMN_NAME"];
//TODO: Do something useful with columnName here
}
}
}
restrictions
定义为
string[] restrictions = new string[] { null, null, tableName };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.