Onega

a lot of VC++ posts, a few C# posts, and some miscellaneous stuff

Thursday, February 17, 2005

C# and postgreSQL8.0 first connection

//demo c# code snippet

//Onega 2005/02/02

//download and install postgreSQL 8.0

//download and install Npgsql0.7beta4-bin.zip unzip to ..\PostgreSQL\8.0\Npgsql\ms1.1

using System;

//C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\gacutil.exe

//download driver for .NET 1.1

//register Mono.Security.Protocol.Tls.dll and Npgsql.dll with gacutil.exe

//http://gborg.postgresql.org/project/npgsql/download/download.php?branch=devel

//add the following 2 dlls to global assembly cache.

//C:\Program Files\PostgreSQL\8.0\Npgsql\ms1.1\Mono.Security.Protocol.Tls.dll

//C:\Program Files\PostgreSQL\8.0\Npgsql\ms1.1\Npgsql.dll

namespace postgres_net

{

    /// <summary>

    /// Summary description for Class1.

    /// </summary>

    using System;

    using System.Data;

    using Npgsql;



    public class Test

    {

        public static void Main(string[] args)

        {

            string connectionString ="Server=127.0.0.1;Port=5432;User Id=postgres;Password=postgres;Database=template1;";

            //IDbConnection dbcon;

            NpgsqlConnection dbcon = new NpgsqlConnection(connectionString);

            dbcon.Open();

            IDbCommand dbcmd = dbcon.CreateCommand();

            string sql ="select * from pg_database";

            dbcmd.CommandText = sql;

            IDataReader reader = dbcmd.ExecuteReader();

            while(reader.Read())

            {

                if(reader.FieldCount>0)

                {

                    string firstfield = (string)reader[0];                    

                    Console.WriteLine(reader.GetName(0) + ":" +firstfield);

                }

            }

            // clean up

            reader.Close();

            reader = null;

            dbcmd.Dispose();

            dbcmd = null;

            dbcon.Close();

            dbcon = null;

            int sleep_time = 5000;

            Console.WriteLine("Sleep " + sleep_time/1000 +" seconds");

            System.Threading.Thread.Sleep(sleep_time);

        }

    }

}

0 Comments:

Post a Comment

<< Home