一个小问题,关于ExecuteNonQuery()的

jellrey 2005-05-31 03:47:54
这个是.net的帮助中的一个例子函数
//以下为执行SQL语句的函数
public static int uf_usesql(string myExecuteQuery, SqlConnection myConnection)
{
SqlCommand myCommand = new SqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
return myCommand.ExecuteNonQuery();
myConnection.Close();
}

执行一次ok,没有问题!
再执行一次,提示:
未处理的“System.InvalidOperationException”类型的异常出现在 system.data.dll 中。

其他信息: 连接已经打开(state=Open)。

函数中不是已经关闭了吗?
...全文
66 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
pupo 2005-05-31
  • 打赏
  • 举报
回复
直接对myConnection进行open,close操作
机器人 2005-05-31
  • 打赏
  • 举报
回复
哦,应该调整一下
public static int uf_usesql(string myExecuteQuery, SqlConnection myConnection)
{
SqlCommand myCommand = new SqlCommand(myExecuteQuery, myConnection);

try
{
myCommand.Connection.Open();
return myCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
throw ex;
}
finally
{
myConnection.Close();
}
}
机器人 2005-05-31
  • 打赏
  • 举报
回复
像你这个情况使用finally最好。
public static int uf_usesql(string myExecuteQuery, SqlConnection myConnection)
{
try
{
SqlCommand myCommand = new SqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
return myCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
throw ex;
}
finally
{
myConnection.Close();
}
}

jellrey 2005-05-31
  • 打赏
  • 举报
回复
瞎了我的狗眼,没有看到.呵呵.真是低级的错误阿!谢谢!
xiaohutushen 2005-05-31
  • 打赏
  • 举报
回复
你都已经return myCommand.ExecuteNonQuery();
怎么关啊。根本都走不到关闭的那一步。
你可以自己在改一下

110,530

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧