我想检索列表中所有表的列列表 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];
我唯一得到的是表的名称。我调试了应用程序,但在行变量中找不到列名。我错过了什么?
最佳答案
尝试以下代码片段(用于 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];
希望这会有所帮助。研发,
附言。在您自己的代码中,作为调试建议:放置一个断行并确保 sourceDataTable !=null
关于c# - 使用 GetSchema 检索表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24415102/