2016-04-21 84 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,"'","''") 

解决你的问题。