ASP.NET更新数据库报错:Connection property has not been initialized求助
问题分析与解决方案
这个错误的原因很明确:你创建的第二个SqlCommand对象insert1没有关联到数据库连接,所以执行ExecuteNonQuery()的时候,它不知道该用哪个连接去操作数据库。
直接修复错误
你需要给insert1指定要使用的连接,有两种方式:
- 在构造
SqlCommand的时候,把连接对象作为第二个参数传入:
SqlCommand insert1 = new SqlCommand("update tbl_Post set likeCount="+newVal+ " where tbl_Post.Id=" + content, conn);
- 或者单独设置
Connection属性:
SqlCommand insert1 = new SqlCommand("update tbl_Post set likeCount="+newVal+ " where tbl_Post.Id=" + content); insert1.Connection = conn;
另外注意你的SQL语句里likeCount="+newVal+ "where这里少了一个空格,应该改成likeCount="+newVal+ " where,不然会生成语法错误的SQL。
更安全更规范的优化方案
不过上面的写法存在SQL注入风险,而且没有正确释放数据库资源,推荐使用参数化查询和using语句来改进代码:
protected void Button1_Click(object sender, EventArgs e) { string contentId = Request.QueryString["ContentID"]; if(string.IsNullOrEmpty(contentId)) { // 处理ContentID为空的情况,比如提示用户参数无效 return; } string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString; // 使用using语句自动释放连接资源,无需手动调用Close using(SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); // 第一步:获取当前likeCount,采用参数化查询避免注入 int oldVal = 0; using(SqlCommand cmd = new SqlCommand("Select likeCount from tbl_Post where Id = @ContentId", conn)) { cmd.Parameters.AddWithValue("@ContentId", Convert.ToInt16(contentId)); using(SqlDataReader dr = cmd.ExecuteReader()) { if(dr.Read()) { oldVal = Convert.ToInt16(dr["likeCount"]); } } } int newVal = oldVal + 1; // 第二步:更新likeCount,同样使用参数化查询 using(SqlCommand updateCmd = new SqlCommand("update tbl_Post set likeCount = @NewVal where Id = @ContentId", conn)) { updateCmd.Parameters.AddWithValue("@NewVal", newVal); updateCmd.Parameters.AddWithValue("@ContentId", Convert.ToInt16(contentId)); updateCmd.ExecuteNonQuery(); } } }
额外优化建议
其实你可以把查询和更新合并成一条SQL语句,这样只需要一次数据库交互,效率更高,还能避免并发问题(比如多个用户同时点赞时,可能会出现计数不准确的情况):
protected void Button1_Click(object sender, EventArgs e) { string contentId = Request.QueryString["ContentID"]; if(string.IsNullOrEmpty(contentId)) { return; } string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString; using(SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using(SqlCommand cmd = new SqlCommand("update tbl_Post set likeCount = likeCount + 1 where Id = @ContentId", conn)) { cmd.Parameters.AddWithValue("@ContentId", Convert.ToInt16(contentId)); int affectedRows = cmd.ExecuteNonQuery(); if(affectedRows == 0) { // 没有找到对应的记录,可以做提示处理 } } } }
这种方式直接在数据库层面完成加1操作,不用先查询再更新,既减少了数据库交互次数,也避免了并发场景下的计数错误。
内容的提问来源于stack exchange,提问作者CyberCube
相关产品推荐
相关产品推荐

