I have need to update large amount of database rows at once. I have "order" column that is going to be updated after user changes it by drag and drop. User probably won't have ability to update "order" of 1000 ojects at once, but lets assume he/she will.
I have tried:
iterating over each object calling object.save() in each iteration (1000 calls one after another of course)
making one big query like "UPDATE name SET order = CASE (...) END WHERE id IN (...)"
I have tried this in Django + Django REST Framework and ASP NET MVC 5 C#. When using first method Django is much faster than ASP NET. Using second method Django is blazing fast (20-30 ms), ASP NET needs for it 400-600ms...
It looks strange as in any other case, like generating view, or returning raw JSON data on api call, updating single or few rows ASP NET is always faster.
My Django code:
def post(self, request):
from django.db import connection
photos_order = ""
ids = ""
for photo in request.DATA:
photos_order += " WHEN id = %d THEN %d" % (photo["id"], photo["order"])
ids += "%s, " % (photo["id"])
ids = ids[:-2]
ids = "(" + ids + ")"
cursor = connection.cursor()
query = "UPDATE mydb.photos_photo SET `order` = CASE %s END WHERE id IN %s" % (photos_order, ids)
cursor.execute(query)
row = cursor.fetchone()
return Response(json.dumps({"message": _("ok")}), status=status.HTTP_200_OK)
My ASP NET MVC 5 code:
[HttpPost]
[Authorize]
public HttpResponseMessage UpdatePhotosSorting(IEnumerable<Photo> photos)
{
List<string> photosOrder = new List<string>();
string photosOrderStrings = "";
foreach (Photo photo in photos)
{
photosOrderStrings += String.Format("WHEN PhotoId = {0} THEN {1} ", photo.PhotoId, photo.Order);
}
q = String.Format("UPDATE dbo.Photo SET \"Order\" = CASE {0} ELSE \"Order\" END", photosOrderStrings);
_db.Database.ExecuteSqlCommand(q);
return Request.CreateResponse(HttpStatusCode.OK, "ok");
}
Am I doing something wrong or this is just how it works? Is MSSQL Express really that slower than MySQL?
A have to add that Django works under Apache + WSGI + MySQL (but also development runserver does mentioned job in ~35-40ms), and ASP NET was tested on IIS Express 8 + MSSQL Express.