[Mono-list] Npgsql error
Emil Emilov
emil at emilov.de
Thu Aug 4 17:16:36 EDT 2005
Cool, a question on that:
What happens if a exception occurs?
I meand close() gets called at the end of the using block, but does it get also called when an exception occurs (sort of finally)?
If yes, I'm changing my programming style :)
Another question, how would it look like if you had to catch an exception (i.e. to rollback a transaction)?
Thanx :)
Jaroslaw Kowalski wrote:
> Hi Emil,
>
>> Also another tip: you don't need to explicitly set connection etc. to
>> null.
>> Cosider following improvement:
>>
>> IDbConnection dbcon;
>> IDbCommand dbcmd;
>> IDataReader reader;
>> try {
>
> ...
>
>> } finally {
>> // cleanup, even if error occurs, closing the reader is important
>> because while it is open no other reader can be opened
>> if (reader!=null) reader.Close();
>> if (dbcmd!=null) dbcmd.Close();
>> if (dbcon!=null) dbcon.Close();
>> }
>
>
> A small tip: Your example is very java-ish. You could reduce the amount
> of code by using C# using() statement which provides automatic cleanup
> for connection, command and reader. I believe that the following is much
> more readable and saves a lot of typing:
>
> =====
> using (IDbConnection c = new NpgsqlConnection("connectionString"))
> {
> c.Open();
> using (IDbCommand cmd = c.CreateCommand())
> {
> cmd.CommandText = "...";
> using (IDataReader reader = cmd.ExecuteReader();
> {
> while (reader.Read())
> {
> }
> }
> }
> ======
--
Emil R. Emilov
-----------------------------------------------------------------------
mailto:emil at emilov.de
http://www.emilov.de
More information about the Mono-list
mailing list