Also another tip: you don't need to explicitly set connection etc. to null.
Cosider following improvement:
IDbConnection dbcon;
IDbCommand dbcmd;
IDataReader reader;
try {
dbcon = new NpgsqlConnection(connectionString);
dbcon.Open();
dbcmd = dbcon.CreateCommand();
string sql =
"SELECT operatingsystem, nodeid " +
"FROM assets";
dbcmd.CommandText = sql;
reader = dbcmd.ExecuteReader();
while(reader.Read()) {
string operatingsystem = (string) reader["operatingsystem"];
string nodeid = (string) reader["nodeid"];
Console.WriteLine("OS: " +
operatingsystem + " " + nodeid);
}
} catch (Exception ex) {
// do stuff, rollback transaction
} 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();
}
Fabian Salamanca Dominguez wrote:
Hi
I tried to compile a simple C# program and access a Postgresql DB but I
got this error in runtime (it compiled with no errors) :
[EMAIL PROTECTED] Mono]$ mcs dbaccess.cs -r:Npgsql.dll -r:System.Data.dll
[EMAIL PROTECTED] Mono]$ mono dbaccess.exe
Unhandled Exception: System.InvalidCastException: Cannot cast from
source type to destination type.
in <0x000e1> dbAccess:Main (System.String[] args)
****************
This is the code:
using System;
using System.Data;
using Npgsql;
public class dbAccess
{
public static void Main(string[] args)
{
string connectionString =
"Server=localhost;" +
"Database=opennms;" +
"User ID=opennms;" +
"Password=opennms;";
IDbConnection dbcon;
dbcon = new NpgsqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql =
"SELECT operatingsystem, nodeid " +
"FROM assets";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()) {
string operatingsystem = (string) reader["operatingsystem"];
string nodeid = (string) reader["nodeid"];
Console.WriteLine("OS: " +
operatingsystem + " " + nodeid);
}
// clean up
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
dbcon = null;
}
}
What am I doing wrong?
Thanks!!!
--
Fabian
------------------------------------------------------------------------
_______________________________________________
Mono-list maillist - [email protected]
http://lists.ximian.com/mailman/listinfo/mono-list
--
Emil R. Emilov
-----------------------------------------------------------------------
mailto:[EMAIL PROTECTED]
http://www.emilov.de
_______________________________________________
Mono-list maillist - [email protected]
http://lists.ximian.com/mailman/listinfo/mono-list