您好我正在尝试将超文本插入到数据库表中。首先,我将所有单词分隔成小写字母并列在listbox1上,这样才能正常工作。
这是我的表格;
id(int),word(nvarchar),sid(int),frequency(int),weight(float),f(boolean) by order
protected void Button1_Click(object sender, EventArgs e)
{
int id=0;
ListBox1.Items.Clear();
string strNew = Request.Form["TextBox1"];
// File.WriteAllText(@"\Users\'uykusuz\Documents\text.txt", strNew);
int n = strNew.Split(' ').Length;
strNew=strNew.ToLower();
var results = strNew.Split(' ').Where(x => x.Length > 1)
.GroupBy(x => x)
.Select(x => new { Count = x.Count(), Word = x.Key })
.OrderByDescending(x => x.Count);
foreach (var item in results)
ListBox1.Items.Add(String.Format("{0} occured {1} times", item.Word, item.Count));
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 = new SqlCommand("insert into word values('" + id + "','" + item.Word.Text + "','0'),'0'),'0'),'0')", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
当我按下按钮时,我总是收到此错误;
ExecuteNonQuery需要一个开放且可用的连接。该 连接的当前状态已关闭。
EDIT1:
foreach (var item in results) {
con.Open();
id++;
SqlCommand cmd = new SqlCommand("insert into word values('" + id + "','" + item.Word + "','0','0','0','0')", con);
cmd.ExecuteNonQuery();
con.Close();
}
我已经改变了这样但现在我收到了这个错误
连接未关闭。连接的当前状态是打开的。
答案 0 :(得分:0)
尝试将最后一行代码更改为我的示例。每次迭代结果集时,都会关闭与数据库的连接。
using (conn){
conn.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 = new SqlCommand("insert into word values('" + id + "','" + item.Word.Text + "','0'),'0'),'0'),'0')", con);
cmd.ExecuteNonQuery();
}
}
答案 1 :(得分:0)
您必须在
之后关闭连接 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 = new SqlCommand("insert into word values('" + id + "','" + item.Word.Text + "','0'),'0'),'0'),'0')", con);
cmd.ExecuteNonQuery();
}
}
con.close();