【问题标题】:Querying postgres from c# using npgsql使用 npgsql 从 c# 查询 postgres
【发布时间】:2017-08-20 09:32:29
【问题描述】:

我已经在我的 Windows 机器上安装了 postgres 并开始在 POC 上工作。我能够从 Windows 命令行连接到数据库。但是,我无法从 C# 应用程序连接。

我的连接字符串似乎有一些问题。我已经阅读了多个教程,但每个教程都有自己的方式来提供连接字符串参数。有没有提供主机名、端口、用户名、密码和数据库的标准方式。

我正在尝试使用 rest api 进行查询。嗯,我做对了。

// GET api/values
[HttpGet]
public IActionResult Get()
{
   Test test = new Test();
   return Ok(test.Table2Json());
}

using Npgsql;
using System;

namespace Zeiss.MCCNeo.DataMigration.Utilities
{
  public class Test
  {
     private readonly NpgsqlConnection conn;
     public Test()
     {

     conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;" +
                                    "Password=postgres;Database=postgres;");
     //also tried using this
     conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User                                       
                                   Id=postgres;" +                              
                                   "Password=postgres;Database=postgres;");
     }

     public string Table2Json()
     {
         string value = null;
         NpgsqlCommand command = new NpgsqlCommand("select * from test", 
                                        conn);
         NpgsqlDataReader dr = command.ExecuteReader();
         while (dr.Read())
         {
         value = dr[0].ToString();
         }
         return value;
         }
    }
 }

例外:

-       $exception  {System.InvalidOperationException: Connection is not open
   at Npgsql.NpgsqlConnection.CheckReadyAndGetConnector()
   at Npgsql.NpgsqlCommand.<ExecuteDbDataReader>d__92.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
   at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at Npgsql.NpgsqlCommand.ExecuteReader()
   at Zeiss.MCCNeo.DataMigration.Utilities.Test.Table2Json() in c:\users\inpyadav\documents\visual studio 2017\Projects\DataMigration\Zeiss.MCCNeo.DataMigration.Utilities\Test.cs:line 19
   at DataMigration.Controllers.ValuesController.Get() in c:\users\inpyadav\documents\visual studio 2017\Projects\DataMigration\DataMigration\Controllers\ValuesController.cs:line 18
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__27.MoveNext()}  System.InvalidOperationException

【问题讨论】:

    标签: c# postgresql


    【解决方案1】:

    为什么不打开错误消息中所说的连接?

    conn.Open();

    【讨论】:

    • 谢谢你,我错过了。
    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2017-10-31
    • 2016-03-05
    • 2016-03-18
    相关资源
    最近更新 更多