我正在尝试创建一个考勤表来记录学生参与的活动。创建新活动时会触发以下代码。创建新活动时,我想将所有学生记录插入考勤表,并将默认参与属性标记为false。 (出勤属性是标记出勤率,设为0)
问题是无法填充考勤表。代码将停止在该行继续:numofRecordsAffected = command.ExecuteNonQuery();
我正试图从学生表中获取所有sigstudentid(s)。我不知道在这种情况下是否建议使用foreach(),但是我们将不胜感激。
我需要一个解决方案!
public int InsertAttendance(int num)
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
SqlConnection connect = new SqlConnection();
DataSet dataset = new DataSet();
String sqlText = "SELECT * FROM Student";
connect.ConnectionString = "Data Source=TECKISTTLE; Initial Catalog=Assignment; Integrated Security=True";
command.Connection = connect;
command.CommandText = sqlText;
int numofRecordsAffected = 0;
adapter.SelectCommand = command;
connect.Open();
adapter.Fill(dataset, "StudentData");
sqlText = "";
foreach (DataRow item in dataset.Tables["StudentData"].Rows)
{
sqlText += " INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) VALUES(@SIGStudentID,@ActivityId,@Attendance); ";
command.Parameters.Clear();
command.Parameters.Add("@SIGStudentID", SqlDbType.Int);
command.Parameters["@SIGStudentID"].Value = Convert.ToInt32(item["SIGStudentID"]);
command.Parameters.Add("@ActivityId", SqlDbType.Int);
command.Parameters["@ActivityId"].Value = num;
command.Parameters.Add("@Attendance", SqlDbType.Bit);
command.Parameters["@Attendance"].Value = 0;
}
numofRecordsAffected = command.ExecuteNonQuery();
connect.Close();
return numofRecordsAffected;
}
答案 0 :(得分:2)
当您将代码numofRecordsAffected = command.ExecuteNonQuery();
放在foreach
旁边时。
它只执行一次。由于此代码是对表格中INSERT
数据的实际陈述,因此INSERT
只有ROW
个最后一个。
试着把你的代码
numofRecordsAffected = command.ExecuteNonQuery();
在foreach
区块内。然后每行INSERT
。
public int InsertAttendance(int num)
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
SqlConnection connect = new SqlConnection();
DataSet dataset = new DataSet();
String sqlText = "SELECT * FROM Student";
connect.ConnectionString = "Data Source=TECKISTTLE; Initial Catalog=Assignment; Integrated Security=True";
command.Connection = connect;
command.CommandText = sqlText;
int numofRecordsAffected = 0;
adapter.SelectCommand = command;
connect.Open();
adapter.Fill(dataset, "StudentData");
sqlText = "";
numofRecordsAffected = 0;
sqlText = "INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) VALUES(@SIGStudentID,@ActivityId,@Attendance); ";
command.CommandText = sqlText;
foreach (DataRow item in dataset.Tables["StudentData"].Rows)
{
command.Parameters.Clear();
command.Parameters.AddWithValue("@SIGStudentID", Convert.ToInt32(item["SIGStudentID"]);
command.Parameters.AddWithValue("@ActivityId", num);
command.Parameters.AddWithValue("@Attendance", 0);
numofRecordsAffected += command.ExecuteNonQuery();
}
connect.Close();
return numofRecordsAffected;
}
答案 1 :(得分:0)
你可能通过使用循环来使它复杂化,并且可以做这样的事情:
"INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) select SIGStudentID, " + num + " as ActivityId, 0 as Attendance from Student;"
参考: