我正在尝试使用 SqlDataAdaptor 中的查询填充我的DataSet。我不明白的是为什么我必须在 Fill 中特别说明表名,当我已经给 SqlDataAdapter 查询哪个表时。
看下面的代码,查询字符串中已经有“FooTable”了,为什么我在SqlDataAdapter.Fill中又需要“FooTable”?
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FooTable", connectionString);
DataSet ds = new DataSet();
da.Fill(ds, "FooTable");
请您参考如下方法:
实际上,在这种情况下您不必这样做,因为您处理的是单个结果集。以下是 MSDN 的相关摘录:
When the query specified returns multiple results, each result set is placed in a separate table. Additional result sets are named by appending integral values to the specified table name (for example, "Table", "Table1", "Table2", and so on). Since no table is created for a query that does not return rows, if you were to process an insert query followed by a select query, the table created for the select query would be named "Table", because it is the first table created. Applications using column and table names should ensure that conflicts with these naming patterns does not occur. The Fill method supports scenarios where the DataSet contains multiple DataTable objects whose names differ only by case. In such situations, Fill performs a case-sensitive comparison to find the corresponding table, and creates a new table if no exact match exists.
以上摘自this page在 MSDN 的 SqlDataAdaptor.Fill() 文档上。
因此,如果您的查询是一个存储过程或产生多个结果集的其他类型的查询,您需要指定 Fill 命令应该使用哪个结果集。这就是第二个参数的作用。否则,假设是由 Fill 命令本身做出的。
通常,如果您只是从表中进行选择,结果集与您从中选择的源表同名。
