本文介绍了连接没有关闭。连接的当前状态是打开的。如何解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一部分代码如下,它一直显示错误连接未关闭。连接的当前状态已打开。I have a part of code as following and it keep showing an error "The connection was not closed. The connection's current state is open.private void load_gridview() { con.Open(); SqlCommand cmd = new SqlCommand("SP_Display_Periodicals", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable t1 = new DataTable(); da.Fill(t1); con.Close(); if (t1.Rows.Count > 0) { GridView1.DataSource = t1.DefaultView; GridView1.DataBind(); } else { GridView1.DataSource = null; GridView1.DataBind(); } }} 我的尝试:What I have tried:I've closed the connection but it still shows an error "The connection was not closed. The connection's current state is open."推荐答案using (SqlConnection con = new SqlConnection(strConnect)) { con.Open(); ... }这样系统将为您处理关闭和处理。您还应该使用使用带有SqlCommand和其他对象的块。 2)尝试... catch ... finally块也是一个好主意!That way the system will handle Close and Dispose for you. You should also use using blocks with SqlCommand and other objects as well.2) A try...catch...finally block is also a good idea!if( con.State==ConnectionState.Closed) { con.Open(); }引用:错误连接是连接的当前状态是打开的。error "The connection was not closed. The connection's current state is open. 消息告诉您在代码中的其他位置打开了连接。通常在最后一个打开之前的部分。 调试器可以帮助你。 当你不明白你的代码在做什么或为什么它做它做的时候,答案是调试器。 使用调试器查看代码正在做什么。只需设置断点并查看代码执行情况,调试器允许您逐行执行1行和在执行时检查变量,这是一个令人难以置信的学习工具。 调试器 - 维基百科,免费的百科全书 [ ^ ] 在Visual Studio 2010中进行调试 - 初学者指南 [ ^ ] 使用Visual Studio 2010进行基本调试 - YouTube [ ^ ] 调试器在这里显示你的代码是什么做和你的任务是比较它应该做什么。 调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。the message tells you that you left the connection opened somewhere else in your code. Usually in the last part that opened one just before.The debugger may help you.When you don't understand what your code is doing or why it does what it does, the answer is debugger.Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.Debugger - Wikipedia, the free encyclopedia[^]Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]Basic Debugging with Visual Studio 2010 - YouTube[^]The debugger is here to show you what your code is doing and your task is to compare with what it should do.There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug. 这篇关于连接没有关闭。连接的当前状态是打开的。如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-26 07:53
查看更多