Obtener una clave primaria de tablas MySql en C # usando OdbcConntion (System.Data.Odbc)

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?

Gracias de antemano.

preguntado el 09 de marzo de 12 a las 15:03

Arguably because Odbc is deprecated, use the MySqlClient and GetSchema(), along with a procedure call for each Table. dev.mysql.com/doc/refman/5.0/en/… stackoverflow.com/questions/2341278/… -

Your comment was the magic key. I did not know that the old interface was deprecated. Finding the right code was a bit of a challenge, as there is sadly no "COLUMN_NAME" on the Indexes collection or "PRIMRY" on the Columns collections, so I have to go through twice, but still, the new version is far better. -

you can answer your own question as a reference for others. -

1 Respuestas

Your comment was the magic key. I did not know that the old interface was deprecated. Finding the right code was a bit of a challenge, as there is sadly no "COLUMN_NAME" on the Indexes collection or "PRIMRY" on the Columns collections, so I have to go through twice, but still, the new version is far better.

public String GetPrimaryKey(String strTable)
{
    try
    {
        Boolean bIsPrimary = false;
        String strIndexName = null;
        String strColumnName = null;
        String[] strRestricted = new String[4] { null, null, strTable, null      };
        DataTable oSchemaIndexes = null;
        DataTable oSchemaIndexColumns = null;


        // Make sure that there is a connection.
        if (ConnectionState.Open != this.m_oConnection.State)
            this.m_oConnection.Open();

        // DATABASE: Get the schemas needed.
        oSchemaIndexes = this.m_oConnection.GetSchema("Indexes", strRestricted);
        oSchemaIndexColumns = this.m_oConnection.GetSchema("IndexColumns", strRestricted);

        // Get the index name for the primary key.
        foreach (DataRow oRow in oSchemaIndexes.Rows)
        {
            // If we have a primary key, then we found what we want.
            strIndexName = oRow["INDEX_NAME"].ToString();
            bIsPrimary = (Boolean)oRow["PRIMARY"];
            if (true == bIsPrimary)
                break;
        }

        // If no primary index, bail.
        if (false == bIsPrimary)
            return null;

        // Get the corresponding column name.
        foreach (DataRow oRow in oSchemaIndexColumns.Rows)
        {
            // Get the column name.
            if (strIndexName == (String)oRow["INDEX_NAME"])
            {
                strColumnName = (String)oRow["COLUMN_NAME"];
                break;
            }
        }

        return strColumnName;
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    return null;
}

Respondido el 14 de junio de 19 a las 09:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.