[Mono-list] Npgsql error

Jaroslaw Kowalski jaak at jkowalski.net
Thu Aug 4 15:54:11 EDT 2005


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())
            {
            }
        }
}
======
-- 
Jaroslaw Kowalski
http://blog.jkowalski.net/ 



More information about the Mono-list mailing list