Windows Develop Bookmark and Share   
 index > Windows Forms Data Controls and Databinding > How to get PK from a table via ODBC
 

How to get PK from a table via ODBC

Hello,

I'm pretty new developing with C# and I'm facing a problem.

I need to get the tables PK's via ODBC but I'm unable to get them.  I include a piece of code I use to get it.

I try to connect to any database that accepts ODBC.


using ( connection = new OdbcConnection(connectionString))
{
     // Fake query to obtain an OdbcDataReader
     // and being able to get the table schema
     String queryString = "SELECT * FROM " + tableName + " WHERE 1=0";
     OdbcCommand command = new OdbcCommand(queryString, connection);

     connection.Open();
     // Start checking the properties
     OdbcDataReader reader = command.ExecuteReader();
     dataTable = reader.GetSchemaTable();

     // Enumerating PK
     foreach (DataRow row in dataTable.Rows)
     {
         if (row["ISKEY"].ToString().ToUpper() == "TRUE")  // Always returns FALSE!!!!
         {
             // Adding PK names to an Array
             primaryKeys.Add(row["COLUMNNAME"].ToString());
         }
     }
}


I would very much appreciate your comments.

Thanks in advance,
Norberto
Sirimashen  14 hours 56 minutes ago
I'm not familiar with the method you show.  But if the database supports INFORMATION_SCHEMA, you could query all the primary keys as follows:

SELECT TC.TABLE_CATALOG, TC.TABLE_SCHEMA, TC.TABLE_NAME, CCU.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU ON TC.CONSTRAINT_CATALOG = CCU.CONSTRAINT_CATALOG AND TC.CONSTRAINT_SCHEMA = CCU.CONSTRAINT_SCHEMA AND TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY TC.TABLE_CATALOG, TC.TABLE_SCHEMA, TC.TABLE_NAME, CCU.COLUMN_NAME
BinaryCoder  5 hours 16 minutes ago

You can use google to search for other answers

Custom Search

More Threads

• How to set Value of a DataGridViewComboBoxCell
• Problem creating master/detail form w/customer/orders
• Object reference not set to an instance of an object.
• Windows forms with database
• Host Controls in Windows Forms DataGridView Cells using VB.net
• Data Grid internal optimization
• DateTimePicker Comparisiom with datetimevariable
• Datagrid ColumnStyle MappingName To SubClass of A Collection?
• problem binding first record to dropdown
• Datagrid hyperlink and button column