1. 程式人生 > >ADO.NET基本資料操作(增刪改查)

ADO.NET基本資料操作(增刪改查)

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

namespace 上課內容1
{
    class 對資料的操作
    {
        static void Main(string[] args)
        {
            //ReadDataBySqlDataReader();
            //OperateDataBySqlCommand();
            //ReadDataBySqlDataAdapter();
            //OperateDataSqlDataAdapter();
            OperateDataSqlDataAdapter2();
        }
         /// <summary>
        /// 使用 SqlDataAdapter 來實現操作資料(新增,修改,刪除)。
        /// </summary>
        private static void OperateDataSqlDataAdapter()
        {
            //第一步:構造資料庫連線字串(伺服器,資料庫,連線認證方式:使用者名稱,密碼)。
            string connectionString = "Data Source=.;Initial Catalog=Business;User Id=sa;Password=011;";

            //第二步:例項化 SqlConnection。
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                //第三步:建立 SQL 語句。並構造 SqlDataAdapter 例項。
                SqlDataAdapter adapter = new SqlDataAdapter();
                string queryString = "SELECT TaskID,ProjectID,ModifiedBy,AssignedTo,TaskSummary,TaskDescription,PriorityID,StatusID,Progress,IsDeleted,DateDue,DateModified,DateCreated FROM Tasks";
                adapter.SelectCommand = new SqlCommand(queryString, connection);

                //第四步:使用 SqlDataAdapter 往 DataSet 裡填充資料(Fill方法)。
                DataSet dataset = new DataSet();
                adapter.Fill(dataset, "hello");

                //第五步:往 DataSet 裡新增資料(往資料表 DataTable 裡新增資料行 DataRow)。
                DataRow dr = dataset.Tables["hello"].NewRow();
                dr["TaskID"] = Convert.ToInt32(dataset.Tables["hello"].Compute("max(TaskID)","true"))+1;
                dr["ProjectID"]=1;
                dr["ModifiedBy"]=2;
                dr["AssignedTo"]=1;
                dr["TaskSummary"]="This is the detail summary";
                dr["TaskDescription"]="This is the detail description";
                dr["PriorityID"]=1;
                dr["StatusID"]=1;
                dr["Progress"]=25;
                dr["IsDeleted"]=0;
                dr["DateDue"]=DateTime.Now;
                dr["DateModified"]=DateTime.Now;
                dr["DateCreated"]=DateTime.Now;
                dataset.Tables["hello"].Rows.Add(dr);

                //第六步:構造 Insert 語句,呼叫 SqlDataAdapter 的 Update 方法更新資料庫。
                string sqlInsert = "INSERT INTO Tasks(ProjectID,ModifiedBy,AssignedTo,TaskSummary,TaskDescription,PriorityID,StatusID,Progress,IsDeleted,DateDue,DateModified,DateCreated) VALUES(1,2,1,'This is the detail summary','This is the detail description',1,1,25,0,'2013-10-22','2013-10-22','2013-10-22')";//字元型別用單引號
                adapter.InsertCommand = new SqlCommand(sqlInsert, connection);//此處不是SqlCommand com=new SqlCommand
                adapter.Update(dataset, "hello");

                //第七步:修改 DataSet 中虛表的資料。
                dataset.Tables["hello"].Rows[0]["ProjectID"] = 2;//注意此時為Rows[0]["ProjectId"]

                //第八步:構造 Update 語句,呼叫 SqlDataAdapter 的 Update 方法更新資料庫中的實表。
                string sqlUpdate = "Update Tasks set ProjectID = 2 where TaskID = 1";
                adapter.UpdateCommand = new SqlCommand(sqlUpdate,connection);
                adapter.Update(dataset, "hello");

                //第九步:刪除 DataSet 中虛表的資料。
                dataset.Tables["hello"].Rows[31].Delete();

                //第十步:構造 Delete 語句,呼叫 SqlDataAdapter 的 Update 方法更新資料庫中的實表。
                string sqlDelete = "Delete from Tasks where TaskID = 46";
                adapter.DeleteCommand = new SqlCommand(sqlDelete, connection);
                adapter.Update(dataset, "hello");
            }
        }

        /// <summary>
        /// 使用 SqlDataAdapter 來讀取資料。
        /// </summary>
        private static void ReadDataBySqlDataAdapter()
        {
            //第一步:構造資料庫連線字串(伺服器,資料庫,連線認證方式:使用者名稱,密碼)。
            string connectionString = "Data Source=.;Initial Catalog=Business;User Id=sa;Password=
011;";
//第二步:例項化 SqlConnection。 using (SqlConnection connection = new SqlConnection(connectionString)) { //第三步:建立 SQL 語句。並構造 SqlDataAdapter 例項。 SqlDataAdapter adapter = new SqlDataAdapter(); string queryString = "SELECT TaskID,ProjectID,ModifiedBy,AssignedTo,TaskSummary,TaskDescription,PriorityID,StatusID,Progress,IsDeleted,DateDue,DateModified,DateCreated FROM Tasks"; adapter.SelectCommand = new SqlCommand(queryString, connection); //connection.Open(); //第四步:使用 SqlDataAdapter 往 DataSet 裡填充資料(Fill方法)。 DataSet dataset = new DataSet(); adapter.Fill(dataset, "Tasks"); //第五步:讀取資料,返回結果。 foreach (DataRow row in dataset.Tables["Tasks"].Rows) { string strTemp = string.Format("{0},{1}", row[0], row[1]); Console.WriteLine(strTemp); } Console.Read(); } } /// <summary> /// 使用 SqlDataAdapter 來實現操作資料(新增,修改,刪除)方法2(節省中間的 SQL 語句). /// </summary> private static void OperateDataSqlDataAdapter2() { //第一步:構造資料庫連線字串(伺服器,資料庫,連線認證方式:使用者名稱,密碼)。 string connectionString = "Data Source=.;Initial Catalog=Business;User Id=sa;Password=
011;";
//第二步:例項化 SqlConnection。 using (SqlConnection connection = new SqlConnection(connectionString)) { //第三步:建立 SQL 語句。並構造 SqlDataAdapter 例項。 SqlDataAdapter adapter = new SqlDataAdapter(); string queryString = "SELECT TaskID,ProjectID,ModifiedBy,AssignedTo,TaskSummary,TaskDescription,PriorityID,StatusID,Progress,IsDeleted,DateDue,DateModified,DateCreated FROM Tasks"; adapter.SelectCommand = new SqlCommand(queryString, connection); //第四步:構造 SqlCommandBuilder 例項(後臺自動完成SQL語句)。 SqlCommandBuilder builder = new SqlCommandBuilder(adapter); //第五步:使用 SqlDataAdapter 往 DataSet 裡填充資料(Fill方法)。 DataSet dataset = new DataSet(); adapter.Fill(dataset, "Tasks"); //第六步:新增 DataSet 虛表中的資料。 DataRow dr = dataset.Tables["Tasks"].NewRow(); dr["TaskID"] = Convert.ToInt32(dataset.Tables["Tasks"].Compute("max(TaskID)","true")) +1; dr["ProjectID"] = 1; dr["ModifiedBy"] = 2; dr["AssignedTo"] = 1; dr["TaskSummary"] = "This is the detail summary"; dr["TaskDescription"] = "This is the detail description"; dr["PriorityID"] = 1; dr["StatusID"] = 1; dr["Progress"] = 25; dr["IsDeleted"] = 0; dr["DateDue"] = DateTime.Parse("2013-10-23"); dr["DateModified"] = DateTime.Parse("2013-10-23"); dr["DateCreated"] = DateTime.Parse("2013-10-23"); dataset.Tables["Tasks"].Rows.Add(dr); //第七步:修改 DataSet 虛表中的資料。 dataset.Tables["Tasks"].Rows[0]["ProjectID"] = 1; //第八步:刪除 DataSet 虛表中的資料。 dataset.Tables["Tasks"].Rows[30].Delete(); //第九步:整體更新資料庫實表。 builder.GetUpdateCommand(); adapter.Update(dataset, "Tasks"); //第十步:顯示 dataset 中虛表中的內容。 foreach (DataRow row in dataset.Tables["Tasks"].Rows) { string strTemp = string.Format("{0},{1}", row[0], row[1]); Console.WriteLine(strTemp); } Console.Read(); } } /// <summary> /// 使用 SqlDataReader 讀資料 /// </summary> private static void ReadDataBySqlDataReader() { //第一步:構造資料庫連線字串(伺服器,資料庫,連線認證方式:使用者名稱,密碼)。 string connectionString = "Data Source=.;Initial Catalog=Business;User Id=sa;Password=
011;";
//第二步:例項化 SqlConnection。 using (SqlConnection connection = new SqlConnection(connectionString)) { //第三步:建立 SQL 語句。並構造 SqlCommand 例項。 string queryString = "SELECT TaskID,ProjectID,ModifiedBy,AssignedTo,TaskSummary,TaskDescription,PriorityID,StatusID,Progress,IsDeleted,DateDue,DateModified,DateCreated FROM Tasks"; SqlCommand command = new SqlCommand(queryString, connection); //第四步:開啟資料庫。 connection.Open(); //第五步:執行命令。 SqlDataReader reader = command.ExecuteReader(); //第六步:讀取資料,返回結果。 try { while (reader.Read()) { string strTemp = string.Format("{0},{1}", reader["TaskID"].ToString(), reader["AssignedTo"].ToString()); Console.WriteLine(strTemp); } Console.Read(); } finally { // Always call Close when done reading. reader.Close(); } } } /// <summary> /// 修改資料庫中的資料。 /// </summary> private static void OperateDataBySqlCommand() { //第一步:構造資料庫連線字串(伺服器,資料庫,連線認證方式:使用者名稱,密碼)。 string connectionString = "Data Source=.;Initial Catalog=Business;User Id=sa;Password=
011;";
//第二步:例項化 SqlConnection。 using (SqlConnection connection = new SqlConnection(connectionString)) { //第三步:建立 SQL 語句。並構造 SqlCommand 例項。 string sqlInsert = "INSERT INTO Tasks(ProjectID,ModifiedBy,AssignedTo,TaskSummary,TaskDescription,PriorityID,StatusID,Progress,IsDeleted,DateDue,DateModified,DateCreated) VALUES(1,2,1,'This is the detail summary','This is the detail description',1,1,25,0,'2013-10-23','2013-10-23','2013-10-23')"; SqlCommand com = new SqlCommand(sqlInsert, connection); com.CommandType = CommandType.Text;//此處不要忘記 //第四步:開啟資料庫。 connection.Open(); //第五步:執行命令。 int intResult = com.ExecuteNonQuery(); //第六步:讀取資料,返回結果。 if (intResult >= 1) { Console.WriteLine("資料插入成功!"); Console.Read(); } else { Console.WriteLine("資料插入失敗!"); Console.Read(); } } } }}