2016-04-21 137 views
0

我想插入一些單詞,我作爲一個項目保存。我的項目是asp.net web項目。我想爲每個單詞生成id並保留4個字段null.There數據庫中的字表中有6個字段.id字長fr布爾量。在Asp.net中插入項目集合

當我運行該項目時,我得到這個錯誤。

ExecuteNonQuery需要一個開放且可用的Connection。連接的當前狀態將關閉。

這裏的代碼,

using (con){ 
    con.Open(); 

    foreach (var item in results) {//here trying to insert word its id and some other informations but for now they can stay null(yes,null allowed for them) 
     id++; 
     SqlCommand cmd= con.CreateCommand(); 
     cmd.CommandText= "insert into word values('"+id+"','"+item.Word+"','"+0+"','"+0+"','"+0+"','"+0+"')"; 

     cmd.ExecuteNonQuery(); 
     con.Close(); 
    } 

編輯:

我提出con.Close了迭代循環,但現在在這裏我得到這個錯誤;

'/'應用程序中的服務器錯誤。 's'附近語法不正確。在字符'''後面的字符 未使用的引號。

using (con){ 
     con.Open(); 

     foreach (var item in results) {//here trying to insert word its id and some other informations but for now they can stay null(yes,null allowed for them) 
      id++; 
      SqlCommand cmd= con.CreateCommand(); 
      cmd.CommandText= "insert into word values('"+id+"','"+item.Word+"','"+0+"','"+0+"','"+0+"','"+0+"')"; 

      cmd.ExecuteNonQuery(); 

     } con.Close(); 
} } 
+2

您正在關閉for循環的每次迭代中的連接。 –

+0

我已將它移到外面,它給了我這個錯誤「附近語法不正確」 字符串')'後面未加上引號。「 – user1953051

+0

你可以更新你的問題,包括你的代碼,因爲它是現在? –

回答

3

在您的代碼:

using (con){ 
    con.Open(); 

    foreach (var item in results) { 
     //here trying to insert word its id and some other informations but for now they can stay null(yes,null allowed for them) 
     id++; 
     SqlCommand cmd= con.CreateCommand(); 
     cmd.CommandText= "insert into word values('"+id+"','"+item.Word+"','"+0+"','"+0+"','"+0+"','"+0+"')"; 

     cmd.ExecuteNonQuery(); 
     con.Close(); 
    } 

你在foreach書面con.Close(),所以在第一圈結束時,你關閉你的連接。

所以這樣你的foreach結束括號後面移動con.Close())

using (con){ 
con.Open(); 

foreach (var item in results) {//here trying to insert word its id and some other informations but for now they can stay null(yes,null allowed for them) 
    id++; 
    SqlCommand cmd= con.CreateCommand(); 
    cmd.CommandText= "insert into word values('"+id+"','"+item.Word+"','"+0+"','"+0+"','"+0+"','"+0+"')"; 

    cmd.ExecuteNonQuery(); 
} 
con.Close(); 
1

移動con.Close(; outside foreach(){}

2

第一次迭代your'e關閉SQL連接。

移動行:「con.Close();」在循環之外。

關於第二個問題,請確保你逃避quatation大關字詞屬性 並嘗試使用字符串格式創建插入串

string word = String.Replace(item.Word,"'","''") 
cmd.CommandText = string.Format("insert into word values('{0}','{1}','{2}','{3}','{4}','{5}')", id, word, 0, 0, 0, 0); 
1

你必須要確保每一個字(item.Word)沒有報價字符,也許

String.Replace(item.Word,"'","''") 

解決你的問題。

相關問題