sqldataAdapter/dataset/datatable的使用

来源:http://www.cnblogs.com/janghe/archive/2017/10/22/7710679.html
-Advertisement-
Play Games

增刪改查 手動增刪改查 ...


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

        private void Form1_Load(object sender, EventArgs e)
        {
            //把cities表中的數據載入到窗體的datagridview
            string connString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            using(SqlConnection sqlconn=new SqlConnection(connString))
            {
                string selectstring = @"select id, cityid, city, provinceid from cities;select * from provinces";

                 #region 單張表
                //創建一個適配器類
                //using(SqlDataAdapter sqladapter=new SqlDataAdapter(selectstring,sqlconn))
                //{

                //    //此時adapter已經連接到了一個表
                //    DataTable dataTable = new DataTable();
                //    //將關聯表的數據填充到dataTable
                //    //sqladapter會自動打開資料庫連接,並執行sql腳本
                //    sqladapter.Fill(dataTable);
                //    //this.dataGridView1.DataSource = dataTable;
                //    List<cities> mycitylist = new List<cities>();

                //    //類定義時欄位{get;set;}不寫顯示不出來
                //    foreach(DataRow datarow in dataTable.Rows)
                //    {
                //        Console.WriteLine(datarow["id"]+" "+datarow[1]);
                //        //把每一行數據封裝成city類 
                //            mycitylist.Add(new cities(){
                //            id=int.Parse(datarow["id"].ToString()),
                //            cityid=int.Parse(datarow["cityid"].ToString()),
                //            city=datarow["city"].ToString(),
                //            provinceid = int.Parse(datarow["provinceid"].ToString())
                //        });
                //    }
                //    //把datatable的數據轉儲成List<city>類型
                //    this.dataGridView1.DataSource = mycitylist;
                    #endregion

                    #region 多張表
                using(SqlDataAdapter sqlDataAdapter =new SqlDataAdapter(selectstring,sqlconn))
                {
                    DataSet dataset=new DataSet();
                    sqlDataAdapter.Fill(dataset);
                    this.dataGridView1.DataSource = dataset.Tables[0];
                }
                    #endregion

                }

            }

        }

 增刪改查

 private void button1_Click(object sender, EventArgs e)
        {
            //把dataGridView修改的數據保存到資料庫中
            string connString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            string selectstring = @"select id, cityid, city, provinceid from cities;select * from provinces";
            using(SqlDataAdapter dataAdapter=new SqlDataAdapter(selectstring,connString))
            {
                //拿到修改完了之後的datatable
                DataTable dt = this.dataGridView1.DataSource as DataTable;
                //修改後dt的變化映射到資料庫中對應表格的變化
                //幫助dataAdapter生成相關的CRUD 的SqlCommand
                using (SqlCommandBuilder sqlcomBulider = new SqlCommandBuilder(dataAdapter))
                {
                    dataAdapter.Update(dt);
                }
            }
            MessageBox.Show("保存成功");

手動增刪改查

public static SqlDataAdapter CreateCustomerAdapter(
    SqlConnection connection)
{
    SqlDataAdapter adapter = new SqlDataAdapter();

    // Create the SelectCommand.
    SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
        "WHERE Country = @Country AND City = @City", connection);

    // Add the parameters for the SelectCommand.
    command.Parameters.Add("@Country", SqlDbType.NVarChar, 15);
    command.Parameters.Add("@City", SqlDbType.NVarChar, 15);

    adapter.SelectCommand = command;

    // Create the InsertCommand.
    command = new SqlCommand(
        "INSERT INTO Customers (CustomerID, CompanyName) " +
        "VALUES (@CustomerID, @CompanyName)", connection);

    // Add the parameters for the InsertCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");

    adapter.InsertCommand = command;

    // Create the UpdateCommand.
    command = new SqlCommand(
        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
        "WHERE CustomerID = @oldCustomerID", connection);

    // Add the parameters for the UpdateCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    SqlParameter parameter = command.Parameters.Add(
        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.UpdateCommand = command;

    // Create the DeleteCommand.
    command = new SqlCommand(
        "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

    // Add the parameters for the DeleteCommand.
    parameter = command.Parameters.Add(
        "@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.DeleteCommand = command;

    return adapter;
}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 首先配置防火牆 CentOS 7.0預設使用的是firewall作為防火牆 1.關閉firewall: systemctl stop firewalld.service #停止firewall systemctl disable firewalld.service #禁止firewall開機啟動或者 ...
  • C#使用互斥量(Mutex)實現多進程併發操作時多進程間線程同步操作(進程同步)的簡單示例代碼及使用方法。代碼經過測試,可供參考,也可直接使用。 ...
  • 子窗體1: 主窗體 子窗體2/3 區別:事件是安全的,只能在類的內部觸發。 ...
  • 通過介面實現,實現松耦合。 主窗體 子窗體1 子窗體2、3 ...
  • C# 編寫的代碼通過VS編譯器生成 dll 或 exe ,很容易被一些反編譯工具查看到源碼或對源碼進行修改。為防止代碼被反編譯或被篡改,我們可以進行一定的防範措施。但不能杜絕,因為DotNet編寫代碼運行必須編譯成IL 中間語言,IL是很規則,同時也很好反編譯。 反編譯防範措施: 設置項目代碼反彙編 ...
  • Cookie Cookie 提供了一種在 Web 應用程式中存儲用戶特定信息的方法。例如,當用戶訪問您的站點時,您可以使用 Cookie 存儲用戶首選項或其他信息。當該用戶再次訪問您的網站時,應用程式便可以檢索以前存儲的信息。所以Cookie也可以在頁面間傳遞值。Cookie通過HTTP頭在瀏覽器和 ...
  • 做日誌組件時,常常會記錄調用者信息,通常都是通過反射來獲取相應信息。不過.Net 4.5引入了三個新的特性,即CallerFilePathAttribute,CallerLineNumberAttribute和CallerMemberNameAttribute。這三個特性都只能應用於參數並且只有在應 ...
  • 有一個習慣,每天翻看不同的技術博客,將其中感覺寫的不錯而且會用到的知識點進行收藏。下麵分享幾個自己感覺不錯的文章。 mysql 資料庫優化: http://www.cnblogs.com/qcloud1001/p/6814585.html http://www.cnblogs.com/qcloud1 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...