shade999
shade999

Reputation: 79

How to execute a select query on database using C# Firebird and display it in shell?

I just started learning C# in Visual Studio and I got a task to do. I have to connect to a SQL database, execute a select query and display the results using Firebird. I have read through a lot of articles, but I got stuck since everyone is telling to do a different thing. Can somebody help me and explain how this works?

using System;
using FirebirdSql.Data.FirebirdClient;

namespace ConsoleApp1
{
    class Program
    {
        static public void Main()
        {
            using (var con = new FbConnection("database=SECRET.FB;user=SYSDBA;password=masterkey;DataSource=sereverip;Port=3050"))
            {
                con.Open();
                using (var transaction = con.BeginTransaction())
                {
                    FbCommand result = new FbCommand("SELECT n.nrdokwew, n.datadok, k.nazwaskr FROM nagl n JOIN kontrah k on (n.id_kontrah = k.id_kontrah)");
                    result.ExecuteNonQuery();
                }
            }
        }
    }
}

Upvotes: 2

Views: 3210

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 108994

You're executing a query, so using ExecuteNonQuery() is the wrong method (that is for executing things like updates, deletes, DDL, etc). You need to use ExecuteReader(), and then iterate over the rows:

See this example:

using (var connection = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey"))
{
  connection.Open();
  using (var transaction = connection.BeginTransaction())
  {
      using (var command = new FbCommand("select * from demo", connection, transaction))
      {
          using (var reader = command.ExecuteReader())
          {
              while (reader.Read())
              {
                  var values = new object[reader.FieldCount];
                  reader.GetValues(values);
                  Console.WriteLine(string.Join("|", values));
              }
          }
      }
  }
}

Upvotes: 2

Related Questions