ADO.NET入門

什麼是ADO.NET

ADO.NET就是一組類庫,這組類庫可讓咱們經過程序的方式訪問數據庫,就像System.IO下的類用類操做文件同樣, System.Data.這組類是用來操做數據庫(不光是MSSql Server),它提供了統一的編程接口讓操做其它數據庫(Access、Oracle等)的方式和操做MSSql Server一致。html

ADO.NET中的五個主要對象

1、Connection

Connection:主要是開啓程序和數據庫之間的鏈接。沒有利用鏈接對象將數據庫打開,是沒法從數據庫中取得數據的。Close和Dispose的區別,Close之後還能夠Open,Dispose之後則不能再用。git

2、Command

Command:主要能夠用來對數據庫發出一些指令,例如能夠對數據庫下達查詢、新增、修改、刪除數據等指令,以及調用存在數據庫中的存儲過程等。這個對象是架構在Connection 對象上,也就是Command 對象是透過鏈接到數據源。sql

3、DataAdapter

DataAdapter:主要是在數據源以及DataSet 之間執行數據傳輸的工做,它能夠透過Command 對象下達命令後,並將取得的數據放入DataSet 對象中。這個對象是架構在Command對象上,並提供了許多配合DataSet 使用的功能。數據庫

4、DataSet

DataSet:這個對象能夠視爲一個暫存區(Cache),能夠把從數據庫中所查詢到的數據保留起來,甚至能夠將整個數據庫顯示出來,DataSet是放在內存中的。DataSet 的能力不僅是能夠儲存多個Table 而已,還能夠透過DataAdapter對象取得一些例如主鍵等的數據表結構,並能夠記錄數據表間的關聯。DataSet 對象能夠說是ADO.NET 中重量級的對象,這個對象架構在DataAdapter對象上,自己不具有和數據源溝通的能力;也就是說咱們是將DataAdapter對象當作DataSet 對象以及數據源間傳輸數據的橋樑。DataSet包含若干DataTable、DataTableTable包含若干DataRow編程

5、DataReader

DataReader:當咱們只須要循序的讀取數據而不須要其它操做時,可使用DataReader 對象。DataReader對象只是一次一筆向下循序的讀取數據源中的數據,這些數據是存在數據庫服務器中的,而不是一次性加載到程序的內存中的,只能(經過遊標)讀取當前行的數據,並且這些數據是隻讀的,並不容許做其它的操做。由於DataReader 在讀取數據的時候限制了每次只讀取一筆,並且只能只讀,因此使用起來不但節省資源並且效率很好。使用DataReader 對象除了效率較好以外,由於不用把數據所有傳回,故能夠下降網絡的負載。服務器

總結

ADO.NET 使用Connection 對象來鏈接數據庫,使用Command 或DataAdapter對象來執行SQL語句,並將執行的結果返回給DataReader 或 DataAdapter ,而後再使用取得的DataReader 或DataAdapter 對象操做數據結果。網絡

一些栗子:

ADO.NET入門——ExecuteNonQuery

class Program
    {
        static void Main(string[] args)
        {
            //連接字符串
            const string conStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
            //鏈接通道
            SqlConnection conn = new SqlConnection(conStr);
            //打開連接
            conn.Open();
            //命令對象
            SqlCommand comm = new SqlCommand();
            //指定連接通道
            comm.Connection = conn;
            //即將執行的sql命令
            comm.CommandText = "update Students set StudentName=StudentName";
            //提交命令到數據庫
            //ExecuteNonQuery()  執行對數據庫的增刪改,返回受影響的行數,
            //適合:insert、delete、update(對於其餘語句返回-1)
            int result = comm.ExecuteNonQuery();
            //關閉連接
            conn.Close();
            Console.WriteLine("({0} 行受影響)",result);
            Console.ReadKey();
        }
    }

ADO.NET入門——ExecuteScalar

class Program
    {
        static void Main(string[] args)
        {
            //連接字符串
            const string conStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
            //鏈接通道
            SqlConnection conn = new SqlConnection(conStr);
            //打開連接
            conn.Open();
            //命令對象
            SqlCommand comm = new SqlCommand();
            //指定連接通道
            comm.Connection = conn;
            //即將執行的sql命令
            comm.CommandText = "select count(*) from Students";
            //提交命令到數據庫
            //ExecuteScalar()	執行查詢,返回結果集的首行首列
            object result = comm.ExecuteScalar();
            //關閉連接
            conn.Close();
            Console.WriteLine("總共有{0}條數據", result);
            Console.ReadKey();
        }
    }

ADO.NET入門——ExecuteReader

public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 使用ExecuteReader讀取一行數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOnce_Click(object sender, EventArgs e)
        {
            SqlDataReader dr = ExecuteReader("select top 1 * from Students");
            Student student = ConvertSqlDataReaderToStudent(dr);
            //爲了讓數據可以在DataGridView裏顯示,
            List<Student> list = new List<Student>()
            {
                student
            };
            dgvStudentList.DataSource = list;
        }

        /// <summary>
        /// 使用ExecuteReader讀取多行行數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMore_Click(object sender, EventArgs e)
        {
            SqlDataReader dr = ExecuteReader("select * from Students");
            List<Student> list = ConvertSqlDataReaderToStudents(dr);
            dgvStudentList.DataSource = list;
        }

        /// <summary>
        /// 獲取 SqlDataReader
        /// </summary>
        /// <param name="cmdText"></param>
        /// <returns></returns>
        private SqlDataReader ExecuteReader(string cmdText)
        {
            //鏈接通道
            SqlConnection conn = new SqlConnection(ConStr);
            //打開連接
            if (conn.State != ConnectionState.Open)
                conn.Open();
            //命令對象
            SqlCommand comm = new SqlCommand();
            //指定連接通道
            comm.Connection = conn;
            //即將執行的sql命令
            comm.CommandText = cmdText;
            //提交命令到數據庫
            //ExecuteReader(CommandBehavior.CloseConnection),
            //在執行該命令時,若是關閉關聯的 DataReader 對象,則關聯的 Connection 對象也將關閉
            SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
            return dr;
        }

        /// <summary>
        /// 將 SqlDataReader 對象轉換爲 Student對象
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Student ConvertSqlDataReaderToStudent(SqlDataReader dr)
        {
            if (!dr.Read()) return null;
            Student student = new Student
            {
                StudentId = (int)dr["StudentId"],
                StudentName = dr["StudentName"].ToString(),
                StudentGender = (bool)dr["StudentGender"],
                StudentAge = (int)dr["StudentAge"],
                GradeId = (int)dr["GradeId"]
            };
            return student;
        }

        /// <summary>
        /// 將 SqlDataReader 對象轉換爲 Student列表
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private List<Student> ConvertSqlDataReaderToStudents(SqlDataReader dr)
        {
            List<Student> list = new List<Student>();
            while (dr.Read())
            {
                Student student = new Student
                {
                    StudentId = (int)dr["StudentId"],
                    StudentName = dr["StudentName"].ToString(),
                    StudentGender = (bool)dr["StudentGender"],
                    StudentAge = (int)dr["StudentAge"],
                    GradeId = (int)dr["GradeId"]
                };
                list.Add(student);
            }
            return list;
        }
    }

    /// <summary>
    /// 學生實體類
    /// </summary>
    public class Student
    {
        #region Model

        /// <summary>
        /// 主鍵
        /// </summary>
        public int StudentId { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string StudentName { get; set; }

        /// <summary>
        /// 性別 true:男; false:女
        /// </summary>
        public bool StudentGender { get; set; }

        /// <summary>
        /// 年齡
        /// </summary>
        public int StudentAge { get; set; }

        /// <summary>
        /// 所屬班級主鍵
        /// </summary>
        public int GradeId { get; set; }

        #endregion Model
    }

ADO.NET入門——DataAdapter

public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = ExecuteDataTable("select * from Students");
            dgvStudentList.DataSource = dt;
        }

        /// <summary>
        /// 獲取 DataTable
        /// </summary>
        /// <param name="cmdText"></param>
        /// <returns></returns>
        private DataTable ExecuteDataTable(string cmdText)
        {
            //實例化一個 SqlDataAdapter
            SqlDataAdapter da = new SqlDataAdapter(cmdText, ConStr);
            //實例化一個 DataTable
            DataTable dt = new DataTable();
            //將數據填充到 dt
            da.Fill(dt);
            return dt;
        }
    }

ADO.NET入門——Parameters

public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 綁定數據到 datagridview
        /// </summary>
        private void BindData()
        {
            //查詢語句
            string sql = "select * from Students";
            //標記是否有 where關鍵字
            bool hasWhere = false;
            List<SqlParameter> parameters=new List<SqlParameter>();
            if (txtName.Text.Trim()!="")
            {
                sql += " where StudentName like @name";
                hasWhere = true;
                parameters.Add(new SqlParameter("name", string.Format("%{0}%", txtName.Text.Trim())));
            }

            if (nudAge.Text.Trim()!="")
            {
                if (!hasWhere)
                {
                    sql += " where StudentAge = @age";
                }
                else
                {
                    sql += " and StudentAge = @age";
                }
                parameters.Add(new SqlParameter("age", nudAge.Text.Trim()));
            }
            

            DataTable dt = ExecuteDataTable(sql, parameters.ToArray());

            dgvStudentList.DataSource = dt;
        }

        /// <summary>
        /// 獲取 DataTable
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="parameters">qlParameters 對象</param>
        /// <returns></returns>
        private DataTable ExecuteDataTable(string cmdText,params SqlParameter[] parameters)
        {
            //實例化一個 SqlDataAdapter
            SqlDataAdapter da = new SqlDataAdapter(cmdText, ConStr);
            //設置參數
            da.SelectCommand.Parameters.AddRange(parameters);
            //實例化一個 DataTable
            DataTable dt = new DataTable();
            //將數據填充到 dt
            da.Fill(dt);
            return dt;
        }

        private void btnParameters_Click(object sender, EventArgs e)
        {
            BindData();
        }
    }

ADO.NET入門——Transaction

public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn=new SqlConnection(ConStr))
            {
                conn.Open();
                //開啓事務
                SqlTransaction transaction = conn.BeginTransaction();
                
                try
                {
                    string sql = "update Banks set Money+=1000 where id=3";
                    //用SqlTransaction初始化SqlCommand
                    SqlCommand comm = new SqlCommand(sql, conn,transaction);
                    comm.ExecuteNonQuery();
                    sql = "update Banks set Money-=1000 where id=2";
                    comm.CommandText = sql;
                    comm.ExecuteNonQuery();
                    transaction.Commit();
                    MessageBox.Show("轉帳成功");
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    MessageBox.Show("轉帳失敗\n" + ex.Message);
                }
            }
        }
    }

ADO.NET入門——StoredProcedure

public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnNoParameter_Click(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("usp_selectStudents", ConStr);
            //用存儲過程來解釋命令字符串
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgvStudents.DataSource = dt;
            lblOutPut.Text = "";
            lblResult.Text = "";
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("usp_selectStudents", ConStr);
            //用存儲過程來解釋命令字符串
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            //設置參數,和參數化查詢一致
            da.SelectCommand.Parameters.Add(new SqlParameter("name", "周"));
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgvStudents.DataSource = dt;
            lblOutPut.Text = "";
            lblResult.Text = "";
        }

        private void btnOutPut_Click(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("usp_selectStudents", ConStr);
            //用存儲過程來解釋命令字符串
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            //設置參數,和參數化查詢一致
            da.SelectCommand.Parameters.Add(new SqlParameter("name", "周"));
            da.SelectCommand.Parameters.Add(new SqlParameter("sumAge",SqlDbType.Int));
            //指定參數是輸出參數
            da.SelectCommand.Parameters["sumAge"].Direction = ParameterDirection.Output;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgvStudents.DataSource = dt;
            //獲取輸出參數
            object outPut = da.SelectCommand.Parameters["sumAge"].Value;
            lblOutPut.Text = "輸出參數是:" + outPut;
            lblResult.Text = "";
        }

        private void btnResult_Click(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("usp_selectStudents", ConStr);
            //用存儲過程來解釋命令字符串
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            //設置參數,和參數化查詢一致
            da.SelectCommand.Parameters.Add(new SqlParameter("name", "周"));
            da.SelectCommand.Parameters.Add(new SqlParameter("sumAge", SqlDbType.Int));
            da.SelectCommand.Parameters.Add(new SqlParameter("count", SqlDbType.Int));
            //指定參數是輸出參數
            da.SelectCommand.Parameters["sumAge"].Direction = ParameterDirection.Output;
            //指定參數是返回值參數
            da.SelectCommand.Parameters["count"].Direction = ParameterDirection.ReturnValue;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgvStudents.DataSource = dt;
            //獲取輸出參數
            object outPut = da.SelectCommand.Parameters["sumAge"].Value;
            //獲取返回值參數
            object result = da.SelectCommand.Parameters["count"].Value;
            lblOutPut.Text = "輸出參數是:" + outPut;
            lblResult.Text = "返回值是是:" + result;
        }
    }

 

下載DEMO架構

相關文章
相關標籤/搜索