本文介绍了C#连接到一个postgres数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次连接到数据库,但我有一些问题

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();



    }
}

}

可能是什么问题?是否正确写入了NpgsqlConnection字符串?

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

如何解决这个问题?

提前感谢!

推荐答案

您从不将 NpgsqlConnection 指派给您的 NpgsqlCommand ,并且您不需要为您的 NpgsqlDataReader 提供查询以解决即时问题。

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.

此外,使用() -statement在中至少包装 NpgsqlConnection 一个好主意,以确保连接始终关闭,即使有一个异常。

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", con);
                NpgsqlDataReader dr= cmd.ExecuteReader();
                if (dr.Read())
                {
                    boolfound=true;
                    Console.WriteLine("connection established");
                }
                if(boolfound==false)
                {
                    Console.WriteLine("Data does not exist");
                }
                dr.Close();
            }
        }
    }
}

这篇关于C#连接到一个postgres数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 08:34