【发布时间】:2011-04-01 09:15:10
【问题描述】:
我的应用程序停止工作。我测试了我的存储过程,它确实返回了 3 行(太大,无法在此处重新发布)。在 Visual Studio 的输出中,它随后会说:
(1 row(s) affected)
(3 row(s) returned)
@RETURN_VALUE = 0
Finished running [dbo].[GetCaseDocumentFile].
为什么我不能将它放入名为 dtResult 的数据表中?命令 sqlDataAdapter.Fill(dtResult) 应该这样做。相反,我在调试模式下查看它时会得到 {}。
string connectionString = @"Data Source=34.56.55.251;Initial Catalog=DBXXX;User ID=xx;Password=XXXXXXXX;";
string queryString = "GetCaseDocumentFile";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("@key", 200012);
connection.Open();
// Works! Three lines are returned.
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
reader.Close();
}
// Does not work! dtResult remains empty. {}
DataTable dtResult = new DataTable();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(command);
sqlDataAdapter.Fill(dtResult);
DataTable result = dtResult;
}
更新:
没关系。这实际上有效。这是我的测试代码,也是我认为我的真实代码所做的。但我想我忽略了真实代码中的某些内容。
【问题讨论】:
-
SqlConnection 并不是唯一真正应该有 using 语句的东西,SqlCommand、SqlDataReader、Datatable 和 SqlDataAdapter 都有 dispose 方法,并且可能应该包含在 usings 中(除非您手动处理它们)
标签: c# sql-server sqlcommand