0

我的数据库中有这张表(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

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

4

3 回答 3

2

Change your Command Text Like this...

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



cmd.CommandText = "SELECT subject+grade FROM table1 WHERE recordID="+currentRecord;
于 2013-05-09T14:45:28.250 回答
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());
于 2013-05-09T14:56:39.497 回答
0

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

于 2013-05-09T14:51:45.210 回答