使用OdbcConnion(System.Data.Odbc)在C#中获取MySql表PrimaryKey
本文关键字:获取 MySql PrimaryKey OdbcConnion System Data Odbc 使用 | 更新日期: 2023-09-27 18:27:27
我试图使用C-Sharp(C#)在MySQL数据库中检索表的主键,但遇到了问题。
我查看了提供的各种元数据集合和相应的列,但它们都没有提供主键。"表"answers"索引"集合似乎是最有前途的。有趣的是,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属性的人的帖子。
那么我该如何识别主键呢?
提前谢谢。
您的评论是一把神奇的钥匙。我不知道旧的接口被弃用了。找到正确的代码有点困难,因为Indexes集合上没有"COLUMN_NAME",Columns集合上也没有"PRIMRY",所以我必须经历两次,但新版本仍然要好得多。
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;
}