一、連接數據庫
使用SqlSugar執行SQL語句,首先需要連接數據庫。SqlSugar支持多種連接數據庫的方式,如連接字符串、單例、數據庫枚舉等。以下示例展示如何使用連接字符串連接MySQL數據庫:
using SqlSugar; using System.Configuration; ... // 連接字符串 string connectionString = ConfigurationManager.ConnectionStrings["MySqlConnect"].ConnectionString; SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = connectionString, DbType = DbType.MySql, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute });
連接配置類ConnectionConfig包含了連接字符串和數據庫類型,還包括連接的其他設置。
二、執行SQL語句
使用SqlSugar執行SQL語句,需要掌握SqlSugar的ORM操作方法。ORM(Object Relational Mapping)對象關係映射,是一種通過使用描述對象和數據庫之間映射的元數據描述來實現的,用於將對象數據存儲到關係型數據庫中。
以下幾個例子使用了SqlSugar的ORM方法,它們分別是Add、Update、Delete、Query、ExecuteCommand和InsertRange,並依次對應CRUD操作的創建、更新、刪除、查詢、執行和批量插入數據的操作。
三、使用ORM方法
1. Add:創建
使用SqlSugar的ORM方法之一Add,可直接創建一個實例並插入數據庫中。
using SqlSugar; using System.Configuration; ... // 創建表 db.CodeFirst.InitTables(typeof(Students)); // 添加實例 Students student = new Students() { Name = "Tom", Age = 20, Gender = true }; db.Insertable(student).ExecuteCommand();
2. Update:更新
使用SqlSugar的ORM方法之一Update,可根據指定的實例進行數據庫記錄的更新操作。
using SqlSugar; using System.Configuration; ... // 更新實例 var tom = db.Queryable().Where(it => it.Name == "Tom").First(); tom.Age = 21; db.Updateable(tom).ExecuteCommand();
3. Delete:刪除
使用SqlSugar的ORM方法之一Delete,根據指定條件刪除數據庫記錄。
using SqlSugar; using System.Configuration; ... // 根據ID刪除 db.Deleteable().In(new[] { 1, 2 }).ExecuteCommand();
4. Query:查詢
使用SqlSugar的ORM方法之一Query,可進行各種類型的查詢操作。
using SqlSugar; using System.Configuration; ... // 查詢所有 List allStudents = db.Queryable().ToList(); // 查詢單個 var tom = db.Queryable().Where(it => it.Name == "Tom").First(); // 連表查詢 List studentAndClasses = db.Queryable((student, classes) => new JoinQueryInfos( JoinType.Left, student.ClassId == classes.Id)) .Select((student, classes) => new StudentAndClass { Id = student.Id, Name = student.Name, ClassName = classes.Name }) .ToList();
5. ExecuteCommand:執行
使用SqlSugar的ORM方法之一ExecuteCommand,可直接執行SQL語句的操作。
using SqlSugar; using System.Configuration; ... // 直接執行SQL語句 int count = db.Ado.ExecuteCommand("update students set age = age + 1");
6. InsertRange:批量插入
使用SqlSugar的ORM方法之一InsertRange,可完成批量插入多條記錄的操作。
using SqlSugar; using System.Configuration; ... // 新增多條記錄 List students = new List() { new Students{ Name= "Tom", Age= 20, Gender= true}, new Students{ Name= "Jerry", Age= 18, Gender= false} }; db.Insertable(students).ExecuteCommand();
四、結語
SqlSugar是一個強大而易用的ORM框架,基於.NET平台,貼近SQL語句,可以快速地進行各種數據庫操作,提高了程序開發效率。上述內容是SqlSugar執行SQL語句的基礎內容,希望對您有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/287258.html