如何在SQL中获得一行字符串?

用户名

这是我的桌子

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<string, string>();

            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 (Dictionary<string, string> column in rows)
{
    interchange.DownloadBlacklist.id = column["id"] ;
    interchange.DownloadBlacklist.first4 = column["first4"];
    interchange.DownloadBlacklist.last4 = column["last4"];
    interchange.DownloadBlacklist.status =  column["status"];
}

最简单的方法是什么?由于我设法提取信息,但是我仅获得表的最后一行,而没有获得如何尝试实现的信息。

莫希特·什里瓦斯塔瓦(Mohit Shrivastava)

这可能为您解决问题

SqlDataReader render = cmd.ExecuteReader();
List<string> IdList = new List<string>();
List<string> First4List = new List<string>();
List<string> Last4List = new List<string>();
List<string> ReasonList = new List<string>();
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<string>对于所有四列将添加从sql读取的所有数据。

然后正常循环读取数据,并将所有数据分别添加到列表中。

读取数据并将其输入列表后,只需,使用Join将其加入。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Bash中,如何在文件的每一行之后添加字符串?

如何在连续写入的日志文件的每一行中添加日期字符串

如何在连续写入的日志文件的每一行中添加日期字符串

在Python中,如何在一行代码中创建n个字符的字符串?

如何获得多行字符串中第一行的长度?

如何在一行中替换多个字符串?

如何在简单的字符串变量中获取最后一行-C#

如何在Groovy中的字符串匹配之前在文件中插入一行

如何在一行中拆分和修剪字符串

如何在Python中的一行用法中将f字符串与b字符串合并

如何在bash中每隔一行的内容上打印其他字符串?

熊猫如何在每一行中对连接的字符串进行排序?

如何在txt文件的第一行中的每一行中写入字符串

如何获得匹配字符串之后的第一行,而不管字符串是否存在

如何在一行中搜索带有特殊符号的字符串

如何在一行中第一个字符后匹配字符串

如何在一行中以字符串形式获得输出?

如何在iOS中向UITableView的最后一行添加带字符串的一行?

如何在列表中的字符串及其索引显示在同一行上?

如何在一行中搜索字符串,然后从那里删除到行尾

如何在一行中打印列表中的所有字符串?

如何在一行中从<a>字符串中抓取链接?

如何在一行中打印多个字符串数组输出

如何在文件的第n列和第一行中添加字符串?

如何在linux文件中的一行编辑字符串

如何在一行字符串中获取剩余的拆分字符串或使用 substr() 函数

如何在pyspark的数据框中的每一行中查找字符串

如何提取一行中的字符串

如何在同一行中打印字符串和整数?