插入

Dapper 插入操作

  1. Dapper 提供 Execute() 擴充方法,用來執行新增、刪除、修改 SQL,回傳受影響的資料列數(int)
  2. 插入實作思路:手動撰寫帶有參數佔位符 @參數名INSERT SQL;傳入實體物件自動對應參數,避免發生 SQL 注入。
  3. 語法格式:INSERT INTO 資料表名(欄位1,欄位2...) VALUES(@參數1,@參數2...)

範例

using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using System.Configuration;
using System.Collections.Generic;

namespace DapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1.讀取連接字串
            var connStr = ConfigurationManager.ConnectionStrings["StudentConnection"].ConnectionString;

            // 2.using 會自動釋放資料庫連線
            using (IDbConnection db = new MySqlConnection(connStr))
            {
                // 3.撰寫插入 SQL,操作 student 資料表
                string sql = @"INSERT INTO student (FirstName, LastName, Email) 
                               VALUES (@FirstName, @LastName, @Email)";

                // 4.建立實體物件
                var stu = new Student()
                {
                    FirstName = "foxdevelop",
                    LastName = "com",
                    Email = "admin@foxdevelop.com"
                };

                // 5.執行插入,取得受影響列數
                int rows = db.Execute(sql, stu);

                // 6.查詢驗證寫入的資料
                List<Student> stuList = db.Query<Student>("SELECT * FROM student").ToList();
            }

            Console.ReadKey();
        }
    }

    // Student 實體類別(屬性名稱必須與 SQL @參數名稱一致)
    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}Code language: HTML, XML (xml)

補充說明

  1. 參數對應規則
    Dapper 會依照實體屬性名稱自動比對 SQL 裡的 @xxx 參數,大小寫不敏感,但建議名稱保持相同。
  2. Execute 回傳值
    int rowsAffected = db.Execute(sql, stu);
  • 回傳 ≥1:插入成功;
  • 回傳 0:沒有任何資料被寫入。
  1. 連接字串設定(App.config)
<configuration>
  <connectionStrings>
    <add name="StudentConnection" 
         connectionString="server=localhost;database=testdb;uid=root;pwd=123456" 
         providerName="MySql.Data.MySqlClient"/>
  </connectionStrings>
</configuration>Code language: HTML, XML (xml)

取得新增資料的自增主鍵ID(MySQL)

如果 student 資料表有自增主鍵 Id,要取得新新增紀錄的編號:

string sql = @"INSERT INTO student (FirstName, LastName, Email) 
               VALUES (@FirstName, @LastName, @Email);
               SELECT LAST_INSERT_ID();";

long newStudentId = db.ExecuteScalar<long>(sql, stu);Code language: HTML, XML (xml)

插入

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *