【发布时间】: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