I want to find out identity column name of a table in MS-Access database using c# code.
Please help me.
This code is part of my 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;
}
Create the connection like this
var cnn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\Data\MyDatabase.mdb\";OLE DB Services=-1");
You can retrieve the primary key (which is not necessarily the same as the AutoNumber column) like this
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
}
}
}
Where restrictions
is defined as
string[] restrictions = new string[] { null, null, tableName };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.