diff --git a/libmysqld/emb_qcache.cc b/libmysqld/emb_qcache.cc
index 0374ab58784efc06029b1f4cceffc04e00df4a4c..4dac154ab8003f15a7ae38716fc857c1649e8e03 100644
--- a/libmysqld/emb_qcache.cc
+++ b/libmysqld/emb_qcache.cc
@@ -284,11 +284,18 @@ uint emb_count_querycache_size(THD *thd)
   MYSQL *mysql= thd->mysql;
   MYSQL_FIELD *field= mysql->fields;
   MYSQL_FIELD *field_end= field + mysql->field_count;
+  MYSQL_ROWS *cur_row=NULL;
+  my_ulonglong n_rows=0;
   
-  *thd->data->prev_ptr= NULL; // this marks the last record
-  MYSQL_ROWS *cur_row= thd->data->data;
-
-  result= 4+8 + (42 + 4*thd->data->rows)*mysql->field_count;
+  if (!field)
+    return 0;
+  if (thd->data)
+  {
+    *thd->data->prev_ptr= NULL; // this marks the last record
+    cur_row= thd->data->data;
+    n_rows= thd->data->rows;
+  }
+  result= 4+8 + (42 + 4*n_rows)*mysql->field_count;
 
   for(; field < field_end; field++)
   {
@@ -315,12 +322,21 @@ void emb_store_querycache_result(Querycache_stream *dst, THD *thd)
   MYSQL *mysql= thd->mysql;
   MYSQL_FIELD *field= mysql->fields;
   MYSQL_FIELD *field_end= field + mysql->field_count;
-  
-  *thd->data->prev_ptr= NULL; // this marks the last record
-  MYSQL_ROWS *cur_row= thd->data->data;
+  MYSQL_ROWS *cur_row= NULL;
+  my_ulonglong n_rows= 0;
+
+  if (!field)
+    return;
+
+  if (thd->data)
+  {
+    *thd->data->prev_ptr= NULL; // this marks the last record
+    cur_row= thd->data->data;
+    n_rows= thd->data->rows;
+  }
 
   dst->store_int((uint)mysql->field_count);
-  dst->store_ll((uint)thd->data->rows);
+  dst->store_ll((uint)n_rows);
 
   for(; field < field_end; field++)
   {
diff --git a/sql/sql_cache.cc b/sql/sql_cache.cc
index aad8d0a5d2cf2c7f5a24e559d14ea36455e3f406..7c31281c9266d211db77a1e1f5a0bee123352263 100644
--- a/sql/sql_cache.cc
+++ b/sql/sql_cache.cc
@@ -653,10 +653,6 @@ void query_cache_abort(NET *net)
 void query_cache_end_of_result(THD *thd)
 {
   DBUG_ENTER("query_cache_end_of_result");
-#ifdef EMBEDDED_LIBRARY
-    query_cache_insert(&thd->net, (byte*)thd, 
-		       emb_count_querycache_size(thd));
-#endif
 
 #ifndef DBUG_OFF
   // Check if we have called query_cache.wreck() (which disables the cache)
@@ -665,6 +661,10 @@ void query_cache_end_of_result(THD *thd)
 
   if (thd->net.query_cache_query != 0)	// Quick check on unlocked structure
   {
+#ifdef EMBEDDED_LIBRARY
+    query_cache_insert(&thd->net, (byte*)thd, 
+		       emb_count_querycache_size(thd));
+#endif
     STRUCT_LOCK(&query_cache.structure_guard_mutex);
     Query_cache_block *query_block = ((Query_cache_block*)
 				      thd->net.query_cache_query);