2010-10-19 56 views
0

代碼:插入寫道

SqlConnection sqlc = new SqlConnection(
         "Data Source=" + Environment.MachineName + @"\SQLEXPRESS;" + 
         "Integrated security=true;" + 
         "database=someDB"); 

SqlCommand sqlcmd; 
string tmp = string.Empty; 

for(int i = 0; i < 100000; i++) 
{ 
    tmp += "inserto into [db].[Files](...) values (...);" 
} 

sqlcmd = new SqlCommand(tmp, sqlc); 
try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } cathc{} 

只插入< 1000寫入 怎麼寫都寫10萬?可能會破壞並創建sqlcmd?

回答

0

你應該把命令分成更小的命令。比方說,每個SqlCommand插入500條記錄,直到插入所有記錄。

int totalRecordsToWrite = 100000; 
int maxRecordsPerCommand = 500; 

SqlConnection sqlc = new SqlConnection(
         "Data Source=" + Environment.MachineName + @"\SQLEXPRESS;" + 
         "Integrated security=true;" + 
         "database=someDB"); 

int currentRecord = 0; 

while (currentRecord < totalRecordsToWrite) 
{ 
    SqlCommand sqlcmd; 
    string tmp = string.Empty; 

    for(int j = 0; j < maxRecordsPerCommand; j++) 
    { 
     currentRecord++; 

     if (currentRecord >= totalRecordsToWrite) 
      break; 

     // Insert record "currentRecord" of the 100000 here. 

     tmp += "inserto into [db].[Files](...) values (...);" 
    } 

    using (sqlcmd = new SqlCommand(tmp, sqlc)) 
    { 
     try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } catch{} 
    } 
} 
+1

plase寫代碼,「病因尚未明瞭 – 4iNo 2010-10-19 05:50:53

+0

或者更好的辦法是優化SQL不要做100000個陳述。也許一個存儲過程也可能是一個更好的選擇? – RPM1984 2010-10-19 05:55:03

+0

並且作爲參數傳遞? – 4iNo 2010-10-19 06:03:29