I am trying to retrieve the Primary Key of a table in a MySQL database using C-Sharp (C#) and running into problem.
I looked at the various MetaData collections offered and the corresponding columns, however none of them offer a primary key. The "Tables" and "Indexes" collection seem the most promising. INTERESTINGLY, OdbcConnection.GetSchema() has a PrimaryKey property/method, however there is no case where the PrimaryKey property yields something other than a null.
Indexes and Tables really did seem like the obvious choice. Yes, the tables in the database have a primary key and the database works.
Here is some code, although for this question none seem really necessary. I chose "Tables" for the purpose of this sample, but one can simply change to "Indexes" (or anything else). Obviously, COLUMN_NAME exists for Tables. I just have that there for whatever, playing.
public String GetPrimaryKey(String strTable)
{
try
{
String strPrimaryKey = null;
String[] strRestricted = new String[4] { null, null, strTable, null };
DataTable oSchema = null;
// Make sure that there is a connection.
if (ConnectionState.Open != this.m_oConnection.State)
this.m_oConnection.Open();
// DATABASE: Get the schema
oSchema = this.m_oConnection.GetSchema("Tables", strRestricted);
// Extract the information related to the primary column, in the format "{System.Data.DataColumn[0]}"
DataColumn[] oPrimaryKeys = oSchema.PrimaryKey;
// Extract: Column Names
foreach (DataRow oRow in oSchema.Rows)
{
// Get the column name.
String strColumnName = oRow["COLUMN_NAME"].ToString();
}
return strPrimaryKey;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
In doing my research, I found it interesting that I could not find any posts from anyone using the GetSchema().PrimaryKey property.
So how can I identify the primary key?
Thanks in advance.