Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# sqlsugar

作者:躲藏我的霸气   发布日期:2026-06-12   浏览:138

using SqlSugar;
using System;

namespace SqlSugarExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建数据库连接配置
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "your_connection_string", // 数据库连接字符串
                DbType = DbType.SqlServer, // 数据库类型,这里以SqlServer为例
                IsAutoCloseConnection = true // 是否自动关闭连接
            });

            // 定义一个简单的实体类
            public class User
            {
                [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
                public int Id { get; set; }
                public string Name { get; set; }
                public int Age { get; set; }
            }

            // 插入数据示例
            var user = new User { Name = "John", Age = 30 };
            db.Insertable(user).ExecuteCommand();

            // 查询数据示例
            var userList = db.Queryable<User>().ToList();
            foreach (var u in userList)
            {
                Console.WriteLine($"Id: {u.Id}, Name: {u.Name}, Age: {u.Age}");
            }

            // 更新数据示例
            var updateUser = new User { Id = 1, Name = "Jack", Age = 35 };
            db.Updateable(updateUser).ExecuteCommand();

            // 删除数据示例
            db.Deleteable<User>(1).ExecuteCommand();
        }
    }
}

解释说明:

  1. 创建数据库连接:使用 SqlSugarClient 类创建一个数据库连接实例,并通过 ConnectionConfig 配置连接字符串、数据库类型和是否自动关闭连接。
  2. 定义实体类:定义了一个简单的 User 实体类,用于表示用户表中的记录。SugarColumn 属性用于指定主键和自增字段。
  3. 插入数据:使用 Insertable 方法将 User 对象插入到数据库中。
  4. 查询数据:使用 Queryable 方法查询所有用户记录,并将其转换为列表进行遍历输出。
  5. 更新数据:使用 Updateable 方法更新指定 ID 的用户记录。
  6. 删除数据:使用 Deleteable 方法删除指定 ID 的用户记录。

希望这个示例能帮助你理解如何使用 SqlSugar 进行基本的 CRUD 操作。

上一篇:c# datatable 添加行

下一篇:c# string 转byte

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站