读取数据 (ADO.Net)

若要从数据库读取数据,请使用 VerticaDataReader(一种 DbDataReader 实施)。此实施可通过分析应用程序在服务器上运行,从而将大量数据快速移出服务器。

要使用 VerticaDataReader 从数据库读取数据:

  1. 创建与数据库的连接

  2. 使用连接创建命令对象。

        VerticaCommand command = _conn.CreateCommand();
    
  3. 创建查询。此查询与示例 VMart 数据库配合工作。

            command.CommandText =
            "SELECT fat_content, product_description " +
            "FROM (SELECT DISTINCT fat_content, product_description" +
            "      FROM product_dimension " +
            "      WHERE department_description " +        "      IN ('Dairy') " +
            "      ORDER BY fat_content) AS food " +
            "LIMIT 10;";
    
  4. 执行读取器以从查询返回结果。以下命令将调用 VerticaCommand 对象的 ExecuteReader 方法以获取 VerticaDataReader 对象。

    VerticaDataReader dr = command.ExecuteReader();
    
  5. 读取数据。数据读取器将在连续流中返回结果。因此,您必须逐行从表中读取数据。以下示例使用 while 循环来完成此操作。

     Console.WriteLine("\n\n Fat Content\t  Product Description");
         Console.WriteLine("------------\t  -------------------");
         int rows = 0;
         while (dr.Read())
         {
            Console.WriteLine("     " + dr[0] + "    \t  " + dr[1]);
            ++rows;
         }
         Console.WriteLine("------------\n  (" + rows + " rows)\n");
    
  6. 完成后,关闭数据读取器以释放资源。

        dr.Close();
    

示例用法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Vertica.Data.VerticaClient;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            VerticaConnectionStringBuilder builder = new VerticaConnectionStringBuilder();
            builder.Host = "192.168.1.10";
            builder.Database = "VMart";
            builder.User = "dbadmin";
            VerticaConnection _conn = new VerticaConnection(builder.ToString());
            _conn.Open();
        VerticaCommand command = _conn.CreateCommand();
            command.CommandText =
                "SELECT fat_content, product_description " +
                "FROM (SELECT DISTINCT fat_content, product_description" +
                "      FROM product_dimension " +
                "      WHERE department_description " +
                "      IN ('Dairy') " +
                "      ORDER BY fat_content) AS food " +
                "LIMIT 10;";
          VerticaDataReader dr = command.ExecuteReader();

         Console.WriteLine("\n\n Fat Content\t  Product Description");
         Console.WriteLine("------------\t  -------------------");
         int rows = 0;
         while (dr.Read())
         {
                Console.WriteLine("     " + dr[0] + "    \t  " + dr[1]);
                ++rows;
         }
         Console.WriteLine("------------\n  (" + rows + " rows)\n");
              dr.Close();
            _conn.Close();
        }
    }
}