2015-05-29 84 views
2

我在ASP.NET的項目。所以我有一個頁面,我正在生成隨機優惠券密鑰。所以用戶輸入數量並生成。插入查詢在for循環中工作不正常

所以我做什麼,我把一個for循環,根據數量和裏面的for循環我創建了一個隨機密鑰並搜索數據庫的關鍵(關鍵是唯一的),然後在數據庫中插入數據。

代碼:

for (int i = 0; i < quantity; i++) 
{ 
    do 
    { 
    couponKey = generateKey(); 
    } while (!SearchEpinKey(couponKey)); 

    conn = new SqlConnection(connString); 
    conn.Open(); 

    using (SqlCommand cmd = new SqlCommand()) 
    { 
     cmd.Connection = conn; 
     cmd.CommandType = CommandType.Text; 
     string query = "INSERT INTO CouponStock (coupon_key, status, created_on)"; 
     query += "VALUES('" + couponKey + "','Unused', GETDATE())"; 
     cmd.CommandText = query; 
     cmd.ExecuteNonQuery(); 

    } 
    conn.Close(); 
} 

在循環中,流量是這樣的:

-Genrate random key 
-Search if random key exists or not in db 
-If found similar then again generate random key 
-Insert the data in DB 

所以,當我運行這個頁面,小批量像10或15,其工作的罰款。但是當我走50或100時,它會插入隨機數的行,比如24時,48時。然後,應用程序會掛起。我在想,Sql服務器在短時間間隔內會遇到很多時間。任何關於如何處理這些問題的指導都會有所幫助。

+0

這是什麼邏輯被用來生成隨機密鑰?您可能能夠將整個過程移至存儲過程。這會更簡單,更快速和準確。 –

+0

@SeanLange感謝您的想法,我會把所有的數據集合,然後執行查詢。我不知道表值參數,但我會在互聯網上搜索。 – sumit

+0

@SeanLange如果我使用內部程序相同的邏輯,將它正常工作? – sumit

回答

0

我能找到的唯一原因是因爲這個

do 
{ 
    couponKey = generateKey(); 
} while (!SearchEpinKey(epinKey)); 

如果您正在使用您的INSERT查詢couponKey,爲什麼要使用SearchEpinKey(epinKey)?你在哪裏搜索數據庫中的couponKey

您分配generateKey()couponKey變量,你正在檢查對epinKey,我相信,當epinKey已經存儲在DB它掛(無限循環),因爲epinKey始終是即使你assing一個新的值相同到couponKey

只是改變這一行

} while (!SearchEpinKey(epinKey)); 

這個

} while (!SearchEpinKey(couponKey)); 
+0

感謝您的編輯。我做了編輯。但問題仍然是一樣的。 – sumit

+0

generateKey()函數的代碼是什麼?請發郵件 –

+0

它只是返回25個字符的隨機數字,沒什麼特別的。 – sumit

0

第一件事,第一,我認爲,我們應該避免打開每個插入一個新的連接,也是我們應該經常使用ASP.Net構建功能參數(例如AddWithValue),因爲它們有助於避免SQL Injection

var couponList = new System.Collections.Generic.List<String>(); 
    var query = "INSERT INTO CouponStock(coupon_key, status, created_on) VALUES(@coupon_key, @status, GETUTCDATE());"; 

    using (SqlConnection conn = new SqlConnection(connString)) 
    { 
     try 
     { 
      conn.Open(); 

      do{ 
       var couponKey = generateKey(); 

       //return early for readability 
       if(!SearchEpinKey(couponKey)) continue; 
       if(couponList.Contains(couponKey)) continue; 

       //add to coupon list to ensure newly generated key does not duplicate 
       couponList.Add(couponKey); 

       SqlCommand cmd = conn.CreateCommand(query); 
       cmd.Parameters.AddWithValue("@coupon_key", couponKey); 
       cmd.Parameters.AddWithValue("@status", "Unused"); 

       cmd.ExecuteNonQuery(); 
      } 
      while (couponList.Count < quantity); 
     } 
     catch (Exception e) 
     { 
      // handle exceptions or re-throw them... 
     } 
     finally 
     { 
      conn.Close(); 
     } 
    }