这是我的表
MY_TABLE | id | first4 | last4 | reason | -------------------------------- | 1 | 123 | 456 | Cancel | | 2 | 123 | 789 | Correct|
问题
它进入循环并获取信息,但最后它只显示最后一行
例:
id = 1 first4 = 123 last4 = 456 reason = cancel
我试图实现的是一个像这样渲染的字符串:
id = 1,2; first4 = 123,123; last4 = 456,789; reason = Cancel,Correct
在C#我使用
try { SqlDataReader render = cmd.ExecuteReader(); while (render.Read()) { while (render.Read()) { column = new Dictionary(); column["id"] = string.Join(",", render["id"]); column["first4"] = string.Join(",", render["first4"]); column["last4"] = string.Join(",", render["last4"]); column["reason"] = string.Join(",", render["reason"]); rows.Add(column); } render.close(); } } catch (Excecption ex) { console.writeline(ex); } finally { conn.Close(); }
打电话给桌子
foreach (Dictionarycolumn in rows) { interchange.DownloadBlacklist.id = column["id"] ; interchange.DownloadBlacklist.first4 = column["first4"]; interchange.DownloadBlacklist.last4 = column["last4"]; interchange.DownloadBlacklist.status = column["status"]; }
实现它的最简单方法是什么?因为我设法提取信息,但我只得到表的最后一行,但不是我试图实现它的方式.
这可能对你有所帮助
SqlDataReader render = cmd.ExecuteReader(); ListIdList = new List (); List First4List = new List (); List Last4List = new List (); List ReasonList = new List (); while (render.Read()) { IdList.Add(render["id"].ToString()); First4List.Add(render["first4"].ToString()); Last4List.Add(render["last4"].ToString()); ReasonList.Add(render["reason"].ToString()); } render.close(); string idstr = string.Join(",", IdList); string first4str = string.Join(",", First4List); string last4str = string.Join(",", Last4List); string reasonstr = string.Join(",", ReasonList);
尝试使用Using
SQL连接和命令.这将帮助您摆脱final
阻塞并使您的连接和命令关闭.
一瞥代码.
创建了字符串列表,即List
对于所有四列,将添加从sql读取的所有数据.
然后在一个循环中正常读取数据并分别添加列表中的所有数据.
一旦在列表中读取并填充了数据,就可以,
使用Join 加入它们.