Reputation: 23
Hello I am trying to insert a hypertext into database table.First I seperated all words make them small letters and list on listbox1 which works right.
And here is my table word;
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();
}
}
I always get this error when I hit the button;
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
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();
}
I have changed like this but Now I am getting this error
The connection was not closed. The connection's current state is open.
Upvotes: 0
Views: 42
Reputation: 345
You have to close the connection after the
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();
Upvotes: 0
Reputation: 1263
Try to change your last lines of code to my example. You closed your connection to database every time when you iterates your results collection.
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();
}
}
Upvotes: 0