robertpas
robertpas

Reputation: 673

C# connecting to a postgres database

This is my first time connecting to a database, but i'm having some problems

using Npgsql;

namespace DBPrj
 {
class Program
{
    static void Main(string[] args)
    {
        bool boolfound=false;
        NpgsqlConnection conn = new NpgsqlConnection("Server=<ip>; Port=5432; User Id=Admin; Password=postgres.1; Database=Test1"); //<ip> is an actual ip address
        conn.Open();

        NpgsqlCommand cmd = new NpgsqlCommand();
        NpgsqlDataReader dr= cmd.ExecuteReader(); //I get InvalidOperationException : The connection is not open.
        if (dr.Read())
        {
            boolfound=true;
            Console.WriteLine("connection established");
        }
        if(boolfound==false)
        {
            Console.WriteLine("Data does not exist");
        }
        dr.Close();
        conn.Close();



    }
}

}

What could be the problem? Is the NpgsqlConnection string written correctly? Could the database be protected from remote access?

How could I fix this problem?

Thanks in advance!

Upvotes: 4

Views: 34815

Answers (2)

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17612

You never assign your NpgsqlConnection to your NpgsqlCommand and you don't supply a query to execute for your NpgsqlDataReader, fixing that should solve the immediate problems.

Also, wrapping at least your NpgsqlConnection in a using()-statement is a good idea to make sure that the connection is always closed, even if there is an exception.

using Npgsql;

namespace DBPrj
{
    class Program
    {
        static void Main(string[] args)
        {
            bool boolfound=false;
            using(NpgsqlConnection conn = new NpgsqlConnection("Server=<ip>; Port=5432; User Id=Admin; Password=postgres.1; Database=Test1"))
            {
                conn.Open();

                NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM Table1", conn);
                NpgsqlDataReader dr= cmd.ExecuteReader();
                if (dr.Read())
                {
                    boolfound=true;
                    Console.WriteLine("connection established");
                }
                if(boolfound==false)
                {
                    Console.WriteLine("Data does not exist");
                }
                dr.Close();
            }
        }
    }
}

Upvotes: 7

Kestami
Kestami

Reputation: 2073

In your connection string you may be missing a semi-colon at the end of database.

Database=Test1"

may need to be;

Database=Test1;"

also - it may be worth wrapping your conn.open() in a try catch statement for user-friendliness and ease of catching errors.

Edit 1:

Just did a little reading. Does NpgsqlCommand need parameters to be passed to it? just in pseudo code, something like;

NpgsqlCommand cmd = new NpgsqlCommand(query, conn);

Upvotes: 1

Related Questions