本文介绍了使用sqlserver从sqldatareader获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我是C#的新手。我试图使用返回类型为'SqlDataReader'的函数填充datareader但不幸的是它给出了一些错误。任何建议都会非常感激。

谢谢,

Akky





Hi guys,
I am new to C#. I am trying to fill a datareader using a function with return type as 'SqlDataReader' but unfortunately its giving some error. Any advice would be really appreciated.
Thanks,
Akky


public static void Main(string[] args)
       {

           SqlDataReader dr = Program.hello("select top 10 firstName,lastName from DimCustomer");
           while (dr.Read())
           {
               Console.WriteLine(dr.GetValue(0));
           }
           Console.ReadLine();

       }
       public static SqlDataReader hello(string query)
       {
           SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=adventure_works;Integrated Security=true;");
           SqlCommand cmd = new SqlCommand(query, con);
           con.Open();
           SqlDataReader dr = cmd.ExecuteReader();
           con.Close();
           return dr;
       }

推荐答案

using System;
using System.Data.SqlClient;

namespace RestApp
{
    class Program
    {
        public static void Main(string[] args)
        {

            SqlDataReader dr = Program.hello("select top 10 firstName,lastName from DimCustomer");
            while (dr.Read())
            {
                Console.WriteLine(dr.GetValue(0));
            }
            Console.ReadLine();

        }
        public static SqlDataReader hello(string query)
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=adventure_works;Integrated Security=true;");
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            return dr;
        }
    }


}


class Program
{
    static SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=adventure_works;Integrated Security=true;");
    public static void Main(string[] args)
    {

        SqlDataReader dr = Program.hello("select top 10 firstName,lastName from DimCustomer");
        while (dr.Read())
        {
            Console.WriteLine(dr.GetValue(0));
        }
        con.Close();
        Console.ReadLine();

    }
    public static SqlDataReader hello(string query)
    {

        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();

        return dr;

    }
}


while (reader.Read())
{

      // Do something with rows
     for( int i = 0; i < reader.FieldCount; i++ ){
     }
//... or
     string field = (string)reader["column1"];
}





详情请参阅这些链接



[]



[]


这篇关于使用sqlserver从sqldatareader获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:16