使用sqlserver从sqldatareader获取数据 [英] getting data from sqldatareader using sqlserver
本文介绍了使用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;
}
推荐答案
只需从con.Close()代码中删除一行,因为SqlDataReader可以在连接模式,它只读取前进模式。
Just remove one line from code that is con.Close() because SqlDataReader works in connected mode and it read forward only mode.
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();
con.Close();
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();
con.Close();
return dr;
}
}
您应该添加一些代码来处理行,如下所示
You should add some code to process rows as follows
while (reader.Read())
{
// Do something with rows
for( int i = 0; i < reader.FieldCount; i++ ){
}
//... or
string field = (string)reader["column1"];
}
详情请参阅这些链接
SqlCommand.ExecuteReader方法 [ ^ ]
SqlDataReader 。阅读 [ ^ ]
这篇关于使用sqlserver从sqldatareader获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文