c#中使用数据读取器读取查询结果

今天有时间了。

在看《c#数据库入门经典》 ,总结数据读取器查询结果。

针对单个结果集使用读取器,有3中方法:

String connString =..;

String sql =@" select Col1Name ,Col2Name from Table ";

SqlConnection conn = new SqlConnection(connString);

conn.Open();

SqlCommand cmd = new SqlCommand(sql, conn);

SqlDataReader rdr = cmd.ExecuteReader();

 

1.使用序数索引器

Console.WriteLine(" Col1 \t Col2 \t " ,rdr[0], rdr[1]);

2.使用列名索引器

Console.WriteLine(" Col1 \t Col2 \t " ,rdr["Col1Name"], rdr[Col2Name]);

3.使用类型访问器

 Console.WriteLine(" Col1 \t Col2 \t " ,rdr.GetString(0), rdr.GetString(1));

 

针对多个数据集使用读取器

 

String connString =..;

String sql1 =@" select Col1Name ,Col2Name from Table where Col1Name='1' ";

String sql2=@" select Col1Name ,Col2Name from Table where Co1Name='2' ";

String sql=sql1+sql2; 

SqlConnection conn = new SqlConnection(connString);

 

   try
            {
                conn.Close();
                conn.Open();

                SqlCommand cmd = new SqlCommand(sql, conn);

                SqlDataReader rdr = cmd.ExecuteReader();

                do
                {
                    while(rdr.Read())
                    {

                        Console.WriteLine("{0} : {1}",rdr[0], rdr[1]);
                    }
                } while (rdr.NextResult()); --读取跨结果集

                rdr.Close();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex);
             
            }
            finally
            {
                conn.Close();
            }

 

 

转载于:https://www.cnblogs.com/macoco/p/3473584.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值