使用Odbc连接在C#中获取MySql表主键(System.Data.Odbc)

时间:2012-03-09 15:45:03

标签: c# mysql primary-key

我正在尝试使用C-Sharp(C#)检索MySQL数据库中表的主键并遇到问题。

我查看了提供的各种MetaData集合以及相应的列,但是它们都没有提供主键。 “表”和“索引”集合似乎是最有希望的。有趣的是,OdbcConnection.GetSchema()有一个PrimaryKey属性/方法,但是不存在PrimaryKey属性产生除null之外的其他东西的情况。

索引和表格确实看起来是显而易见的选择。是的,数据库中的表具有主键,数据库可以正常工作。

这是一些代码,虽然对于这个问题似乎没有必要。我选择“表格”作为此示例的目的,但可以简单地更改为“索引”(或其他任何内容)。显然,COLUMN_NAME存在于Tables中。我只是在那里玩,播放。

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;
}

在进行我的研究时,我发现有趣的是我找不到使用GetSchema()。PrimaryKey属性的任何人的帖子。

那么如何识别主键呢?

提前致谢。

1 个答案:

答案 0 :(得分:2)

你的评论是神奇的关键。我不知道旧的界面已被弃用。找到正确的代码是一个挑战,因为索引集合上没有“COLUMN_NAME”或Columns集合上的“PRIMRY”,所以我必须经历两次,但是,新版本要好得多。

public String GetPrimaryKey(String strTable)

{     尝试     {         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;

}