使用GetSchema检索表的列

时间:2014-06-25 17:33:39

标签: c# mysql sql

我想检索列表matchingTableList中的所有表的列列表:

foreach (var table in matchingTableList)
{
    Console.WriteLine("Analyzing " + table);
    var sourceTableRows = sqlSourceConnection.GetSchema("Columns", new[] {SourceDatabase, null, table, null});
    var destTableRows = sqlDestConnection.GetSchema("Columns", new[] { DestDatabase, null, table, null });
    Console.WriteLine("Number of fields " + sourceTableRows.Rows.Count);
    //iterate through every field in the table
    foreach (var row in sourceTableRows.Rows)
    {
        Console.WriteLine("Analyzing col " + row);
        //if the field is not present, add it to the list containing the added fields for the current table
        if (destTableRows.Columns.Contains((row.ToString()))) continue;
        if (!changedTablesAddedFields[table].Contains(row.ToString()))
        {
            changedTablesAddedFields[table].Add(row.ToString());
        }
    }
}

sourceTableRows.Rows的计数始终为0,即使表中的数据库中包含列也是如此。 我错过了什么?

EDIT1:我可以在

时检索值
var sourceTableRows = sqlSourceConnection.GetSchema("Columns", new[] {null, null, table, null});
var destTableRows = sqlDestConnection.GetSchema("Columns", new[] { null, null, table, null });

但为什么会这样呢?

EDIT2:我发现这是MSSQL的语法:

var sourceTableRows = sqlSourceConnection.GetSchema("Columns", new[] {SourceDatabase, null, table, null});
var destTableRows = sqlDestConnection.GetSchema("Columns", new[] { DestDatabase, null, table, null });

虽然MySQL需要这个:

var sourceTableRows = sqlSourceConnection.GetSchema(" Columns",new [] {null,SourceDatabase,table,null});         var destTableRows = sqlDestConnection.GetSchema(" Columns",new [] {null,DestDatabase,table,null});

但是,当我尝试使用

获取列的名称时
var rowName = (string) row[2];

我唯一得到的是表的名称。我调试了应用程序,我在行变量中找不到列名。我错过了什么?

1 个答案:

答案 0 :(得分:0)

尝试以下代码段(用于SqlCE,但适用于其他版本的SQL Server:只使用相应的SQL对象)。另外,请注意注释,因为它们几乎解释了代码操作逻辑:

        // `ConnectionString` specifies the Database
        SqlCeConnection connectionSql = new SqlCeConnection(ConnectionString);
        connectionSql.Open();

        // create new `DataAdapter` on `connectionSql` and Your `SelectQuery` text
        SqlCeDataAdapter dataAdapterSql = new SqlCeDataAdapter();
        dataAdapterSql.SelectCommand = new SqlCeCommand(SelectQuery, connectionSql);

        // create DataSet
        DataSet dataSet= new DataSet();

        // retrieve TableSchema
        DataTable[] _dataTablesSchema = dataAdapterSql.FillSchema(dataSet, SchemaType.Source);

        // there is only one Table in DataSet, so use 0-index
        DataTable  sourceDataTable = _dataTablesSchema[0];

        // use DataAdapter to Fill Dataset
        dataAdapterSql.Fill(sourceDataTable );

您还可以使用快捷方式缩短代码:

    // there is only one Table in DataSet, so use 0-index
    DataTable sourceDataTable= = dataAdapterSql.FillSchema(dataSet, SchemaType.Source)[0];

希望这会有所帮助。 RGDS,

PS。在您自己的代码中,作为调试建议:设置一个中断行并确保sourceDataTable !=null