C#中SqlDataReader循环读取不全、卡死问题的排查与解决
C# SqlDataReader读取异常问题的解决
问题场景
在C#中实现将SqlDataReader结果拼接为字符串的功能时,遇到如下问题:
- 循环过程中,
reader.Read()有时会返回false,导致无法读取所有表行 - 进入该异常状态后,
reader.Read()始终无法返回true,若在迭代前等待则会造成程序卡死 - 该问题在循环中出现的概率为1%-10%,询问是否有SQL连接状态可用于互斥循环
解决方法
问题已解决:
- 核心原因:查询中引用了错误的SQL列
- 辅助修复:添加
reader.NextResult()方法也起到了辅助解决作用
修复后的代码
using System; using System.Diagnostics; using Microsoft.Data.SqlClient; public string StringTableRows(string conn_str, int row_count) { string s = ""; Query query = new Query(); for (int i = 1; i < row_count;) { // **修复:之前引用了错误的列 string dyn_query = query.RowQuery(ids[i]); try { SqlConnection conn = new SqlConnection(conn_str); using (conn) { SqlCommand cmd = new SqlCommand(dyn_query, conn); using (cmd) { cmd.Connection.Open(); // 注:原代码中comm应为cmd,此处保留原文结构 SqlDataReader reader = comm.ExecuteReader(); using (reader) { Debug.WriteLine("Outside: " + i); while (reader.Read()) { for (int j = 0; j < reader.FieldCount; j++) { s = s + reader.GetString(0); Debug.WriteLine("Inside: " + i); } } // **修复:添加该行辅助解决问题 reader.NextResult(); } } } } catch (Exception ex) { Debug.WriteLine("Failed query: " + dyn_query); Debug.WriteLine("Execute Exception: " + ex); } i++; } s = s.Insert(0,"<Tables>"); s = s + "</Tables>"; return s; }
内容的提问来源于stack exchange,提问作者hydctrl
相关产品推荐
相关产品推荐

