简体   繁体   English

如何使用 C# Firebird 对数据库执行选择查询并将其显示在 shell 中?

[英]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.我刚开始在 Visual Studio 中学习 C#,我有一项任务要做。 I have to connect to a SQL database, execute a select query and display the results using Firebird.我必须连接到 SQL 数据库,执行选择查询并使用 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();
                }
            }
        }
    }
}

You're executing a query, so using ExecuteNonQuery() is the wrong method (that is for executing things like updates, deletes, DDL, etc).您正在执行查询,因此使用ExecuteNonQuery()是错误的方法(即用于执行更新、删除、DDL 等内容)。 You need to use ExecuteReader() , and then iterate over the rows:您需要使用ExecuteReader() ,然后遍历行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM