How to get the primary key
Hello there,
I want to write a function returning the primary key name of a certain
table.
The following function successfully returns the names of all fields of
a table:
public string[] GetFieldNames(string tableName)
{
string[] fieldNames = null;
IDbConnection conn = _factory.CreateConnection(true);
try
{
string[] restrictions = { null, tableName, null };
DataTable dataTable = (conn as
DbConnection).GetSchema("Columns", restrictions);
if (dataTable != null)
{
fieldNames = new string[dataTable.Rows.Count];
for (int i = 0; i < dataTable.Rows.Count; i++)
fieldNames[i] = dataTable.Rows[i]
["COLUMN_NAME"].ToString();
}
return fieldNames;
}
finally
{
conn.Close();
}
}
An interesting part in the upper function is, that the table name is
at the second position in the restrictions array instead on the third,
as I have seen several times in samples found in the internet. In my
case I get the field names with the table name at the second position
in the array.
Now I wrote a function to get the primary key of a table:
public string GetPrimaryKeyName(string tableName)
{
IDbConnection conn = _factory.CreateConnection(true);
try
{
string[] restrictions = { null, tableName,
tableName };
DataTable dataTable = (conn as
DbConnection).GetSchema("PrimaryKeys", restrictions);
if (dataTable != null)
{
if (dataTable.Rows.Count > 0)
return dataTable.Rows[0]
["COLUMN_NAME"].ToString();
}
return null;
}
finally
{
conn.Close();
}
}
That function never returns me the primary key, regardless on which
position the table name is in the restrictions array. I heard that the
upper function does not work for connections based on Oracle. Is that
true?
Regards,
Norbert
Date:Wed, 25 Jul 2007 02:30:12 -0700
Author:
|