日期:2014-05-18  浏览次数:20931 次

VS2005 数据无法写入数据库
这是我的程序: 
主要是想做个访问网站人数的统计 
Global.asax中的代码如下: 
void Application_Start(object sender, EventArgs e) 

// 在应用程序启动时运行的代码 
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=(local);Initial Catalog=countPeople;;Integrated Security=True;Persist Security Info=True"); 
con.Open(); 
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("select * from countPeople",con); 
int count = Convert.ToInt32(cmd.ExecuteScalar()); 
con.Close(); 
Application["total"] = count; 
Application["online"] = 0; 


void Application_End(object sender, EventArgs e) 

// 在应用程序关闭时运行的代码 
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=(local);Initial Catalog=countPeople;;Integrated Security=True;Persist Security Info=True"); 
con.Open(); 
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("update countPeople set num"+Application["total"].ToString(), con); 
cmd.ExecuteNonQuery(); 
con.Close(); 


void Application_Error(object sender, EventArgs e) 

// 在出现未处理的错误时运行的代码 



void Session_Start(object sender, EventArgs e) 

// 在新会话启动时运行的代码 
Session.Timeout = 1; 
Application.Lock(); 
Application["total"] = (int)Application["total"] + 1; 
Application["online"]=(int)Application["online"]+1; 
Application.UnLock(); 


void Session_End(object sender, EventArgs e) 

// 在会话结束时运行的代码。 
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer 
// 或 SQLServer,则不会引发该事件。 
Application.Lock(); 
Application["online"] = (int)Application["online"] - 1; 
Application.UnLock(); 

无法将历史在线人数count写入数据库,调试的时候将www服务关闭也无法更新,盼高人指点!!

------解决方案--------------------
con.Open(); 
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("select * from countPeople",con); 
int count = Convert.ToInt32(cmd.ExecuteScalar()); 
con.Close(); 


你的表结构是什么样的?是不是SQL语句写错了,ExecuteScalar()方法是获得第一行第一列的值哦!你要统计应该是
select count(*) from countPeople吧!
------解决方案--------------------
Application_End?!你不如在Session_End的时候执行更新。

"update countPeople set num"+Application["total"].ToString()这个也有问题。set num=xxx where xxx吧。
------解决方案--------------------
...太长,没耐心..
------解决方案--------------------

------解决方案--------------------
太长,没耐心看。我碰到过这种情况。我那次是变量 超出了字段的长度!
------解决方案--------------------
探讨
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("select * from countPeople",con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();


你的表结构是什么样的?是不是SQL语句写错了,ExecuteScalar()方法是获得第一行第一列的值哦!你要统计应该是
select count(*) from countPeople吧!

------解决方案--------------------
我也同意一楼的看法