问题描述
执行以下操作code离开连接打开,如果有异常?
我使用的是Microsoft SQL Compact Edition数据库。
尝试
{
康涅狄格州的SqlCeConnection =新的SqlCeConnection(的ConnectionString);
conn.Open();
使用(SqlCeCommand CMD =
新SqlCeCommand(选择的东西从SomeTable,康涅狄格州))
{
//做一些东西
}
conn.Close();
}
赶上(例外前)
{
ExceptionManager.HandleException(前);
}
当然,更好的办法是在尝试之前声明一个连接对象,建立try块内的连接,并关闭在finally块?
的SqlCeConnection康恩= NULL;
尝试
{
康恩=新的SqlCeConnection(的ConnectionString);
conn.Open();
使用(SqlCeCommand CMD =
新SqlCeCommand(选择的东西从SomeTable,康涅狄格州))
{
//做一些东西
}
}
赶上(例外前)
{
ExceptionManager.HandleException(前);
}
最后
{
如果(conn将!= NULL)conn.Close();
}
您正在处理 SqlCeCommand
在code用的帮助的方式使用
块,可以为做同样的的SqlCeConnection
。
的SqlCeConnection康恩;
使用(康恩=新的SqlCeConnection(的ConnectionString))
{
conn.Open();
使用(SqlCeCommand CMD =
新SqlCeCommand(选择的东西从SomeTable,康涅狄格州))
{
//做一些东西
}
}
请注意:您可以使用使用
块实现的IDisposable
类
编辑:这是一样的。
尝试
{
康恩=新的SqlCeConnection(的ConnectionString);
conn.Open();
SqlCeCommand CMD = conn.CreateCommand();
cmd.CommandText =...;
cmd.ExecuteNonQuery();
}
最后
{
conn.Close();
}
REF:http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28VS.80%29.aspx
Does the following code leave the connection open if there is an exception?
I am using a Microsoft SQL compact edition database.
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
conn.Close();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
Surely a better way would be to declare a connection object before the try, establish a connection inside the try block and close it in a finally block?
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
finally
{
if( conn != null ) conn.Close();
}
The way you are handling SqlCeCommand
in your code with the help of a using
block, you could do the same for the SqlCeConnection
.
SqlCeConnection conn;
using (conn = new SqlCeConnection(ConnectionString))
{
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
Note: You can use a using
block for classes that implement IDisposable
.
EDIT: This is same as
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "...";
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
ref: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28VS.80%29.aspx
这篇关于正确的方法将在异常情况下的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!