第四章 ADO.NET

--使用DataSet访问数据
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //定义一个需要访问的数据库的信息
            string strCon = "Server=PC-20161029WDCV\SQL2014;Database=StudentDB;Trusted_Connection=True";
            SqlConnection con = new SqlConnection(strCon);

            //打开数据库连接
            con.Open();

            string cmdText = "select * from course";
            SqlDataAdapter da = new SqlDataAdapter(cmdText, con);

            //新建一个DataSet,用于接收查询结果
            DataSet ds = new DataSet();
            da.Fill(ds);

            //关闭数据库连接
            con.Close();

            //将查询结果的第一个表赋值给dt
            DataTable dt = ds.Tables[0];

            txtMsg.Text = "课程号    课程名
";
            
            //foreach (DataRow dr in dt.Rows)
            //{
            //    txtMsg.Text += dr[0].ToString() + "   " + dr[1].ToString()+"
";
            //}

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                txtMsg.Text += dt.Rows[i][0] + "    " + dt.Rows[i][1] + "
";
            }

            lblMsg.Text = "" + dt.Rows.Count + "条数据";


            //txtMsg.Text += dt.Rows[0][0].ToString() + "    "+dt.Rows[0]["课程名"].ToString();

        }
    }
}



--使用sqlDataReader访问数据
  private void Form5_Load(object sender, EventArgs e)
        {
            string str = "server=PC-20171113RBMO;database=StudentDB;Trusted_Connection = True;";
            SqlConnection con = new SqlConnection(str);
            con.Open();
            string s = "select * from course";
            SqlCommand cmd = new SqlCommand(s,con);
            SqlDataReader dr = cmd.ExecuteReader();
            txtmsg.Text = "学号 姓名
";
            int count = 0;
            while (dr.Read())
            {
                txtmsg.Text += dr.GetString(0) + "  " + dr.GetString(1) + "
";
                count++;
            }
            dr.Close();
            con.Close();
            lalmsg.Text = "共有" + count + "条数据";
        }




原文地址:https://www.cnblogs.com/zhang1997/p/7891622.html