0
私はWindowsマシンにpostgresをインストールし、POCの作業を開始しました。私はWindowsのコマンドラインからデータベースに接続することができます。しかし、私はC#アプリケーションから接続することができません。npgsqlを使用してC#からpostgresを照会
接続文字列に問題があるようです。私は複数のチュートリアルを終えましたが、すべてのチュートリアルには、接続文字列パラメータを提供する独自の方法があります。ホスト名、ポート、ユーザー名、パスワード、およびデータベースを与える標準的な方法はありますか。
残りの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
ありがとう、私はそれを逃した。 – dataEnthusiast
問題はありません。慎重にエラーメッセージを読んでください。 – Admir