从字符串中的数据库中保存多个记录

时间:2013-05-09 14:39:38

标签: c# sql sql-server

我的数据库中有这个表(1个学生的记录ID相同,不同学生自动递增1):

id  | firstName | lastName | subject | grade | recordID |
----+-----------+----------+---------+-------+----------+
 1  | John      | Doe      | 1       | A     | 1        |
 1  | John      | Doe      | 2       | B     | 1        |
 3  | Max       | Smith    | 1       | C     | 2        |

使用C#我想将id = 1的数据保存为以下格式的字符串:

Name: John Doe
Details: 1A; 2B
Name: Max Smith
Details: 1C

到目前为止我所做的是:

SqlCommand cmd = _connection.CreateCommand();
string res = null;
cmd.CommandText = "SELECT COUNT(DISTINCT recordID) FROM table1";
int numb = Convert.ToInt32(cmd.ExecuteScalar().ToString());
int currentRecord = 1;

for (int i = 0; i < numb; i++)
{
cmd.CommandText = "SELECT firstname, lastname FROM table1 WHERE recordID="+currentRecord+";";
res += "Name: " + cmd.ExecuteScalar().ToString() + "\n Details: ";

cmd.CommandText = "SELECT subject, grade FROM table1 WHERE recordID="+currentRecord+";";
res += "Details: " + cmd.ExecuteScalar().ToString() + "\n";

currentRecord++
}

这总是将第一条记录保存在字符串中,例如

Name: John
Details: 1
Name: Max
Details: 1

虽然我需要保存多个行和列。请帮忙!

3 个答案:

答案 0 :(得分:2)

更改您的命令文本就像这样......

cmd.CommandText = "SELECT firstname+' '+lastname FROM table1 WHERE recordID="+currentRecord;



cmd.CommandText = "SELECT subject+grade FROM table1 WHERE recordID="+currentRecord;

答案 1 :(得分:1)

我将尝试通过recordID对数据库进行单次调用(假设数量不是千万次)中的所有记录,然后输入循环并在一次记录中提取信息。

这可以通过这样的循环完成(未经测试,只是举例)

string sqlCommand = "SELECT id ,firstName, lastName,subject,grade,recordID " + 
                    "from table ORDER BY recordID";

 int prevID = -1;
 int curID = -1;
 StringBUilder res = new StringBuilder()
 SqlCommand cmd = _connection.CreateCommand();
 cmd.CommandText = sqlCommand;
 SqlDataReader reader = cmd.ExecuteReader()
 while(reader.Read()
 {
     curID = Convert.ToInt32(reader[5]);
     if(curID != prevID)
     {
         prevID = curID;
         res.AppendLine("\r\nName: " + reader[1].ToString() + " " + reader[2].ToString());
         res.Append("Details:");
     }
     res.Append(reader[3].ToString() + reader[4].ToString() + ";";
 }
 Console.WriteLine(res.ToString());

答案 2 :(得分:0)

您使用cmd.ExecuteScalar返回结果第一行的第一个单元格。您需要使用cmd.ExecuteReader来获取比第一个单元格更多的数据。