我的数据库中有这张表(1 个学生的记录 ID 相同,不同学生的记录 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
虽然我需要保存多行和多列。请帮忙!