ado查询

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //一、查询显示
            //引用命名空间using System.Data.SqlClient;
            //1.建立数据链接
            SqlConnection conn = new SqlConnection("server=.;database=data0425;user=sa;pwd=123");

            //2.建立数据命令操作(在数据连接的基础上创建数据命令类)
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from student";
            
            //3.数据库开启
            conn.Open();

            //4.执行数据命令,读取数据库数据
            SqlDataReader dr = cmd.ExecuteReader();
            if(dr.HasRows)
            {
                while(dr.Read())
                {
                    DateTime dt=(DateTime)dr[3];
                    DateTime n=DateTime.Now;
                    

                    Console.WriteLine
                   ("学号:"+dr[0]+
                    "  姓名:"+dr[1]+
                    "  性别:"+(((bool)dr[2])?"":"")+
                    "  年龄:"+(n.Year-dt.Year)+
                    "  生日:"+dt.ToString("yyyy年MM月dd日")+
                    "  分数"+((decimal)dr[4]).ToString("#.##")
                    );
                }
            }


            //5.数据库关闭
            conn.Close();
            





            Console.ReadKey();
        }
    }
}

原文地址:https://www.cnblogs.com/fengsantianya/p/5604587.html