0

I wrote a console app for our elementary school which will read courses, students, coursework (etc) from Google Classrooms and write it to our SQL Server database. This is the first time I have ever used an API and I have very little experience with C#. The program runs successfully, but it takes a long time (over an hour). I think it may be because it is writing one record at a time to the SQL server.

Is there a way with C# that I can alter the code so that when it makes each request, it saves all the records retrieved all at once to something like a temp table and then I can write all the the records for each retrieve to the SQL server with one INSERT statement? (or maybe there is a better way?)

I've pasted the section of code that processes students below, as an example. Note that it retrieves 30 students at a time because that is the max allowed for students. And the sql_students parameterized SQL statement is built earlier in the code.

Any help would be very appreciated.

//=================================================================== // Transfer students

CoursesResource.StudentsResource.ListRequest RequestStudents = service.Courses.Students.List(course.Id);
RequestStudents.PageSize = 30;

// use PageToken and NextPageToken to process all pages results
do
{
    ListStudentsResponse ResponseStudents = RequestStudents.Execute();

    if (ResponseStudents.Students != null && ResponseStudents.Students.Count > 0)
    {
        foreach (var student in ResponseStudents.Students)
        {
            // write the record to sql database 
            try
            {
                using (SqlCommand command = new SqlCommand(sql_students, connection))
                {
                    command.Parameters.AddWithValue("@CourseId", CourseId);
                    command.Parameters.AddWithValue("@StudentUserID", student.UserId ?? string.Empty);
                    command.Parameters.AddWithValue("@StudentFirstName", student.Profile.Name.GivenName ?? string.Empty);
                    command.Parameters.AddWithValue("@StudentLastName", student.Profile.Name.FamilyName ?? string.Empty);
                    command.Parameters.AddWithValue("@StudentEmailAddress", student.Profile.EmailAddress ?? string.Empty);

                    int rowsAffected = command.ExecuteNonQuery();
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        // Get next page token
        RequestStudents.PageToken = ResponseStudents.NextPageToken;
    }
} while (!string.IsNullOrEmpty(RequestStudents.PageToken));
Dale K
  • 25,246
  • 15
  • 42
  • 71
bpnit
  • 3
  • 2

0 Answers0