当前位置: 首页 > article >正文

MongoDB 与 EF Core 深度整合实战:打造结构清晰的 Web API 应用

题纲

    • MongoDB 字符串
      • 连接 URI
      • C# 连接字符串实例
    • 实现一个电影信息查询 demo
      • 创建项目
      • 创建实体
      • 实现 DbContext 上下文
      • 仓储实现
      • 服务实现
      • 控制器实现
      • 服务注册
      • 快照注入数据库连接配置
        • 1. 注册配置类
        • 2. 注入 `IOptionsSnapshot<MongoDbSettings>`
        • 3. 配置文件 appsettings.json 示例
    • 总结

  • 过去,C# 开发者可以使用 MongoDB.Driver(MongoDB 的 C# 驱动程序),但无法获得针对 EF Core 的第一方支持。

  • 现在,随着 MongoDB.EntityFrameworkCore(适用于 EF Core 的官方 MongoDB 提供程序) 的正式发布,开发者在使用 MongoDB 构建生产级工作负载时可以放心地使用 C#EF Core

链接
.NET/C#
MongoDB.Driver
MongoDB.EntityFrameworkCore
MongoDB
  • .NET Nuget 包发布情况:
2024-01-01 2024-04-01 2024-07-01 2024-10-01 2025-01-01 2025-04-01 7.0.0-preview.1 8.0.0---8.3.0 9.0.0-preview.1---9.0.0 .net nuget package Adding GANTT diagram functionality to MongoDB.EntityFrameworkCore

github 项目地址,https://github.com/mongodb/mongo-efcore-provider

MongoDB 字符串

接下来介绍如何使用 MongoDB.Driver 连接到 MongoDB 实例或副本集部署。

连接 URI

连接 URI(也称为连接字符串)可告知驱动程序如何连接到 MongoDB 部署,以及连接后如何进行操作。

标准连接字符串包括以下部分:

字段说明
mongodb://必需。将其标识为标准连接格式中字符串的前缀。
username:password@可选。身份验证凭证。如果包含这些内容,客户端将根据 authSource 中指定的数据库对用户进行身份验证。
host[:port]必需。运行 MongoDB 的主机和可选端口号。如果未包含端口号,则驱动程序将使用默认端口 27017。
/defaultauthdb可选。如果连接字符串包含 username:password@ 身份验证档案但未指定 authSource 选项,则要使用的身份验证数据库。如果您不包含这一内容,客户端将根据 admin 数据库对用户进行身份验证。
?<options>可选。将连接特定选项指定为 = 对的查询字符串。有关这些选项的完整说明,请参阅连接选项。

连接选项 参考,https://www.mongodb.com/zh-cn/docs/drivers/csharp/current/fundamentals/connection/connection-options/#std-label-csharp-connection-options

C# 连接字符串实例

  1. 连接字符串语法
mongodb://<username>:<password>@<host1>:<port1>,<host2>:<port2>,<host3>:<port3>/?replicaSet=<replicaSetName>
  1. 参数说明
  • <username>:MongoDB 的认证用户名(如果没有认证可省略)
  • <password>:MongoDB 的用户密码(如果没有认证可省略)
  • <host1>, <host2>, <host3>:MongoDB 副本集的各个节点 IP 或主机名;
  • <port>:MongoDB 实例的端口号,默认为 27017
  • <replicaSetName>:MongoDB 副本集的名称
  1. 示例代码
var connectionString = "mongodb://admin:password@host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet";var client = new MongoClient(connectionString);
var database = client.GetDatabase("test");
  1. 其他常用选项

你还可以添加额外参数到连接字符串中,例如:

  • ssl=true:启用 SSL 加密连接
  • authSource=admin:指定认证数据库
  • readPreference=secondaryPreferred:优先读取从节点

示例:

mongodb://admin:password@host1:27017,host2:27017,host3:27017/test?replicaSet=myReplicaSet&ssl=true&authSource=admin

实现一个电影信息查询 demo

  • 添加 nuget 包
dotnet add package MongoDB.EntityFrameworkCore --version 9.0.0
  • 当前包版本为 9.0.0

MongoDB.EntityFrameworkCore

MongoDB EF Core 提供程序需要启用实体框架核心8或9。.NET 8或更高版本以及 MongoDB数据库服务器5.0或更高级别,最好是在 支持事务 的配置中。

创建项目

使用 .NET CLI 创建一个名为 MongoDbExampleWeb API 项目,可以使用以下命令:

dotnet new webapi -n MongoDbExample
# 进入项目
cd MongoDbExample
dotnet run

创建实体

创建两个实体类,分别模拟电影信息和电影商品,定义如下:

  • Movie 电影信息
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;namespace MongoDbExample.Database.Collections;public sealed class Movie
{[BsonId][BsonElement("_id")]public ObjectId Id { get; set; }[BsonElement("title")]public string Title { get; set; } = null!;[BsonElement("rated")]public string Rated { get; set; } = null!;[BsonElement("plot")]public string Plot { get; set; } = null!;
}
  • Product 电影商品
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;namespace MongoDbExample.Database.Collections;public sealed class Product
{[BsonId][BsonElement("_id")]public ObjectId Id { get; set; } [BsonElement("name")]public string? Name { get; set; }[BsonElement("price")]public decimal Price { get; set; }
}

实现 DbContext 上下文

  • CinemaAppDbContext
using Microsoft.EntityFrameworkCore;
using MongoDB.Driver;
using MongoDB.EntityFrameworkCore.Extensions;
using MongoDbExample.Database.Collections;namespace MongoDbExample;public sealed class CinemaAppDbContext(ILogger<CinemaAppDbContext> logger,DbContextOptions<CinemaAppDbContext> options) : DbContext(options)
{public DbSet<Product> Products { get; init; }public DbSet<Movie> Movies { get; init; }public static CinemaAppDbContext Create(ILogger<CinemaAppDbContext> logger,IMongoDatabase database){var options = new DbContextOptionsBuilder<CinemaAppDbContext>().UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName).Options;return new CinemaAppDbContext(logger, options);}public static IMongoDatabase GetDatabase(MongoClientSettings clientSettings, string name, MongoDatabaseSettings? dbSettings = null){var client = new MongoClient(clientSettings);return dbSettings is null ? client.GetDatabase(name) : client.GetDatabase(name, dbSettings);}public static IMongoDatabase GetDatabase(string connectionString, string name, MongoDatabaseSettings? dbSettings = null){var client = new MongoClient(connectionString);return dbSettings is null ? client.GetDatabase(name) : client.GetDatabase(name, dbSettings);}protected override void OnModelCreating(ModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);logger.LogInformation("Configuring entity mappings..."); // 实体映射到集合modelBuilder.Entity<Product>().ToCollection("products");modelBuilder.Entity<Movie>().ToCollection("movies");}
}

仓储实现

创建仓储模式,实现上面实体的 crud 操作,实现如下:

  • ICinemaAppRepository,定义仓储规范
using MongoDB.Bson;
using MongoDbExample.Database.Collections;namespace MongoDbExample.Database.Repositorys;public interface ICinemaAppRepository
{#region MovieIAsyncEnumerable<Movie> GetMoviesAsync();Task<Movie?> GetMovieByIdAsync(ObjectId id);Task<(bool isOk, ObjectId id)> AddMovieAsync(Movie movie);Task<(bool isOk, ObjectId id)> UpdateMovieAsync(Movie movie);Task<bool> DeleteMovieAsync(ObjectId id);#endregion#region ProductIAsyncEnumerable<Product> GetProductsAsync();Task<Product?> GetProductByIdAsync(ObjectId id);Task<(bool isOk, ObjectId id)> AddProductAsync(Product product);Task<(bool isOk, ObjectId id)> UpdateProductAsync(Product product);Task<bool> DeleteProductAsync(ObjectId id);#endregion
}
  • CinemaAppRepository 仓储实现

此处使用 partial class (部分类)模拟工程化结构,分别拆分为两个独立的文件 CinemaAppRepository.Movie.csCinemaAppRepository.Product.cs

using MongoDbExample.Database.Repositorys;namespace MongoDbExample.Repositorys;// 实现接口 ICinemaAppRepository
public partial class CinemaAppRepository(ILogger<CinemaAppRepository> logger, CinemaAppDbContext dbContext) : ICinemaAppRepository
{// CinemaAppRepository.Movie.cs// CinemaAppRepository.Product.cs
}
  • CinemaAppRepository.Movie.cs
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDbExample.Database.Collections;namespace MongoDbExample.Repositorys;public partial class CinemaAppRepository
{#region IMovieRepositorypublic async IAsyncEnumerable<Movie> GetMoviesAsync(){var movies = await dbContext.Movies.ToListAsync();foreach (var movie in movies){yield return movie;}}public Task<Movie?> GetMovieByIdAsync(ObjectId id) => dbContext.Movies.FindAsync(id).AsTask();public async Task<(bool isOk, ObjectId id)> AddMovieAsync(Movie movie){if (movie.Id == ObjectId.Empty){movie.Id = ObjectId.GenerateNewId(); // 确保生成新的 ObjectId}await dbContext.Movies.AddAsync(movie);int rcount = await dbContext.SaveChangesAsync();return (rcount > 0, movie.Id);}public async Task<(bool isOk, ObjectId id)> UpdateMovieAsync(Movie movie){dbContext.Movies.Update(movie);int rcount = await dbContext.SaveChangesAsync();return (rcount > 0, movie.Id);}public async Task<bool> DeleteMovieAsync(ObjectId id){int rcount = 0;var movie = await dbContext.Movies.FindAsync(id);if (movie != null){dbContext.Movies.Remove(movie);rcount = await dbContext.SaveChangesAsync();}return rcount > 0;}#endregion
}
  • CinemaAppRepository.Product.cs
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDbExample.Database.Collections;namespace MongoDbExample.Repositorys;public partial class CinemaAppRepository
{#region Productpublic async IAsyncEnumerable<Product> GetProductsAsync(){var products = await dbContext.Products.ToListAsync();foreach (var product in products){yield return product;}}public async Task<Product?> GetProductByIdAsync(ObjectId id){return await dbContext.Products.FindAsync(id);}public async Task<(bool isOk, ObjectId id)> AddProductAsync(Product product){if (product.Id == ObjectId.Empty){product.Id = ObjectId.GenerateNewId(); // 确保生成新的 ObjectId}await dbContext.Products.AddAsync(product);int rcount = await dbContext.SaveChangesAsync();return (rcount > 0, product.Id);}public async Task<(bool isOk, ObjectId id)> UpdateProductAsync(Product product){dbContext.Products.Update(product);int rcount = await dbContext.SaveChangesAsync();return (rcount > 0, product.Id);}public async Task<bool> DeleteProductAsync(ObjectId id){int rcount = 0;var product = await dbContext.Products.FindAsync(id);if (product != null){dbContext.Products.Remove(product);rcount = await dbContext.SaveChangesAsync();}return rcount > 0;}#endregion
}

服务实现

定义服务接口,分别实现如下:

  • IMovieService
using MongoDB.Bson;
using MongoDbExample.Database.Collections;namespace MongoDbExample.Services;public interface IMovieService
{IAsyncEnumerable<Movie> GetMoviesAsync();Task<(bool success, string msg, Movie? data)> GetMovieByIdAsync(ObjectId id);Task<(bool success, string msg, ObjectId id)> CreateMovieAsync(Movie movie);Task<(bool success, string msg, ObjectId id)> UpdateMovieAsync(Movie movie);Task<(bool success, string msg)> DeleteMovieAsync(ObjectId id);
}
  • IProductService
using MongoDB.Bson;
using MongoDbExample.Database.Collections;namespace MongoDbExample.Services;public interface IProductService
{IAsyncEnumerable<Product> GetProductsAsync();Task<(bool success, string msg, Product? Data)> GetProductByIdAsync(ObjectId id);Task<(bool success, string msg, ObjectId Id)> CreateProductAsync(Product product);Task<(bool success, string msg, ObjectId Id)> UpdateProductAsync(Product product);Task<(bool success, string msg)> DeleteProductAsync(ObjectId id);
}

实现接口规范,代码如下:

  • MovieService
using MongoDB.Bson;
using MongoDbExample.Database.Collections;
using MongoDbExample.Database.Repositorys;namespace MongoDbExample.Services;public class MovieService(ICinemaAppRepository _repository) : IMovieService
{#region Moviepublic IAsyncEnumerable<Movie> GetMoviesAsync() => _repository.GetMoviesAsync();public async Task<(bool success, string msg, Movie? data)> GetMovieByIdAsync(ObjectId id){var movie = await _repository.GetMovieByIdAsync(id);if (movie == null) return (false, "Movie not found", null);return (true, "Success", movie);}public async Task<(bool success, string msg, ObjectId id)> CreateMovieAsync(Movie movie){if (string.IsNullOrWhiteSpace(movie.Title))return (false, "Movie title is required.", ObjectId.Empty);var (isOk, id) = await _repository.AddMovieAsync(movie);if (!isOk) return (false, "Failed to add movie.", ObjectId.Empty);return (true, "Movie added successfully.", id);}public async Task<(bool success, string msg, ObjectId id)> UpdateMovieAsync(Movie movie){var existing = await _repository.GetMovieByIdAsync(movie.Id);if (existing == null) return (false, "Movie not found.", ObjectId.Empty);var (isOk, id) = await _repository.UpdateMovieAsync(movie);if (!isOk) return (false, "Failed to update movie.", ObjectId.Empty);return (true, "Movie updated successfully.", id);}public async Task<(bool success, string msg)> DeleteMovieAsync(ObjectId id){var exists = await _repository.GetMovieByIdAsync(id);if (exists == null) return (false, "Movie not found.");var success = await _repository.DeleteMovieAsync(id);if (!success) return (false, "Failed to delete movie.");return (true, "Movie deleted successfully.");}#endregion
}
  • ProductService
using MongoDB.Bson;
using MongoDbExample.Database.Collections;
using MongoDbExample.Database.Repositorys;namespace MongoDbExample.Services;public class ProductService(ICinemaAppRepository repository) : IProductService
{#region Productpublic IAsyncEnumerable<Product> GetProductsAsync() => repository.GetProductsAsync();public async Task<(bool success, string msg, Product? Data)> GetProductByIdAsync(ObjectId id){var product = await repository.GetProductByIdAsync(id);if (product == null) return (false, "Product not found", null);return (true, "Success", product);}public async Task<(bool success, string msg, ObjectId Id)> CreateProductAsync(Product product){if (string.IsNullOrWhiteSpace(product.Name))return (false, "Product name is required.", ObjectId.Empty);var (isOk, id) = await repository.AddProductAsync(product);if (!isOk) return (false, "Failed to add product.", ObjectId.Empty);return (true, "Product added successfully.", id);}public async Task<(bool success, string msg, ObjectId Id)> UpdateProductAsync(Product product){var existing = await repository.GetProductByIdAsync(product.Id);if (existing == null) return (false, "Product not found.", ObjectId.Empty);var (isOk, id) = await repository.UpdateProductAsync(product);if (!isOk) return (false, "Failed to update product.", ObjectId.Empty);return (true, "Product updated successfully.", id);}public async Task<(bool success, string msg)> DeleteProductAsync(ObjectId id){var exists = await repository.GetProductByIdAsync(id);if (exists == null) return (false, "Product not found.");var success = await repository.DeleteProductAsync(id);if (!success) return (false, "Failed to delete product.");return (true, "Product deleted successfully.");}#endregion
}

控制器实现

此处只给出 Products 接口实现(Movies类似)。

using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDbExample.Database.Collections;
using MongoDbExample.Services;namespace MongoDbExample.Controllers;[Route("api/[controller]")]
[ApiController]
public class ProductsController(IProductService productService) : ControllerBase
{[HttpGet]public IAsyncEnumerable<Product> GetProducts() => productService.GetProductsAsync();[HttpGet("{id}")]public async Task<IActionResult> GetProduct(ObjectId id){var (success, msg, data) = await productService.GetProductByIdAsync(id);return success ? Ok(data) : NotFound(new { message = msg });}[HttpPost]public async Task<IActionResult> CreateProduct(Product product){var (success, msg, id) = await productService.CreateProductAsync(product);return success? CreatedAtAction(nameof(GetProduct), new { id }, new { message = msg, id }): BadRequest(new { message = msg });}[HttpPut]public async Task<IActionResult> UpdateProduct(Product product){var (success, msg, id) = await productService.UpdateProductAsync(product);return success? Ok(new { message = msg, id }): BadRequest(new { message = msg });}[HttpDelete("{id}")]public async Task<IActionResult> DeleteProduct(ObjectId id){var (success, msg) = await productService.DeleteProductAsync(id);return success ? Ok(new { message = msg }) : NotFound(new { message = msg });}
}

服务注册

在 Program.cs 中实现服务注册。

using MongoDB.Driver;
using MongoDbExample;
using MongoDbExample.Database.Repositorys;
using MongoDbExample.Repositorys;var builder = WebApplication.CreateBuilder(args);// 添加日志等基础服务
// 创建 ILoggerFactory
var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{loggingBuilder.AddConsole();
});var logger = loggerFactory.CreateLogger<CinemaAppDbContext>();// Add services to the container.// 从环境变量获取连接字符串
var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
if (connectionString == null)
{Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/quick-start/#set-your-connection-string");Environment.Exit(0);
}// 创建 DbContext 实例
var database = CinemaAppDbContext.GetDatabase(connectionString, "sample_mflix");
var cinemaContext = CinemaAppDbContext.Create(logger, database);{var movie = cinemaContext.Movies.First(m => m.Title == "Back to the Future");Console.WriteLine(movie.Plot);
}// 将实例注册为服务
builder.Services.AddSingleton(cinemaContext);
// 注册 ICinemaAppRepository 仓储
builder.Services.AddScoped<ICinemaAppRepository, CinemaAppRepository>();// 添加控制器
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.MapOpenApi();
}app.UseAuthorization();
app.MapControllers();await app.RunAsync();

快照注入数据库连接配置

以上就是使用 MongoDB.EntityFrameworkCore 示例的 demo 实现,获取数据库连接字符串可以使用 快照方式注入,改进如下:

  • MongoDbSettings
public class MongoDbSettings
{public string ConnectionString { get; set; } = "mongodb://localhost:27017";public string DatabaseName { get; set; } = "cinema_app";
}
1. 注册配置类

在 Program.cs 中将 MongoDbSettings 注册为服务,并绑定到配置。

var builder = WebApplication.CreateBuilder(args);// 从 appsettings.json 或其他配置源绑定 MongoDbSettings
builder.Services.Configure<MongoDbSettings>(builder.Configuration.GetSection("MongoDbSettings"));
2. 注入 IOptionsSnapshot<MongoDbSettings>

在需要使用的类中,通过构造函数注入 IOptionsSnapshot<MongoDbSettings>,并获取当前配置快照。

public class SomeService
{private readonly MongoDbSettings _mongoDbSettings;public SomeService(IOptionsSnapshot<MongoDbSettings> optionsSnapshot){_mongoDbSettings = optionsSnapshot.Value;}public void PrintSettings(){Console.WriteLine($"ConnectionString: {_mongoDbSettings.ConnectionString}");Console.WriteLine($"DatabaseName: {_mongoDbSettings.DatabaseName}");}
}
3. 配置文件 appsettings.json 示例

添加 MongoDbSettings 配置:

{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*","MongoDbSettings": {"ConnectionString": "mongodb://localhost:27017","DatabaseName": "cinema_app"}
}

关于 MongoDB 更多信息,请查看官方文档

  • https://www.mongodb.com/zh-cn/docs/

总结

本文详细讲解了如何在 .NET/C# 项目中使用 MongoDB.EntityFrameworkCore 这一官方提供程序,轻松地连接并操作 MongoDB 数据库。文章从基础讲起,介绍了 MongoDB 连接字符串的格式和用法,并通过具体的 C# 示例演示了如何连接到 MongoDB 副本集。随后,通过构建一个完整的电影票信息查询 Web API 应用,逐步展示了基于 EF Core 的数据库上下文(DbContext)、实体类设计、仓储模式(Repository)、服务逻辑以及控制器的具体实现方式。最后,还补充了如何通过配置快照的方式动态注入 MongoDB 的连接配置信息。整篇文章内容由浅入深,结构清晰,适合希望将 .NET 应用与 MongoDB 结合使用的开发者参考学习。

相关文章:

MongoDB 与 EF Core 深度整合实战:打造结构清晰的 Web API 应用

题纲 MongoDB 字符串连接 URIC# 连接字符串实例 实现一个电影信息查询 demo创建项目创建实体实现 DbContext 上下文仓储实现服务实现控制器实现服务注册快照注入数据库连接配置1. 注册配置类2. 注入 IOptionsSnapshot<MongoDbSettings>3. 配置文件 appsettings.json 示例…...

JAVA|后端编码规范

目录 零、引言 一、基础 二、集合 三、并发 四、日志 五、安全 零、引言 规范等级&#xff1a; 【强制】&#xff1a;强制遵守&#xff0c;来源于线上历史故障&#xff0c;将通过工具进行检查。【推荐】&#xff1a;推荐遵守&#xff0c;来源于日常代码审查、开发人员反馈…...

重写B站(网页、后端、小程序)

1. 网页端 1.1 框架 Vue ElementUI axios 1.2 框架搭建步骤 搭建Vue 1.3 配置文件 main.js import {createApp} from vue import ElementUi from element-plus import element-plus/dist/index.css; import axios from "axios"; import router from…...

文档债务拖累交付速度?5大优化策略文档自动化

开发者在追求开发速度的过程中&#xff0c;往往会忽视文档的编写&#xff0c;如省略设计文档、代码注释或API文档等。这种做法往往导致在后期调试阶段需要花费三倍以上的时间来理解代码逻辑&#xff0c;进而形成所谓的文档债务&#xff0c;严重拖累交付速度并造成资源浪费。而积…...

【数据结构与算法】LeetCode 每日三题

如果你已经对数据结构与算法略知一二&#xff0c;现在正在复习数据结构与算法的一些重点知识 ------------------------------------------------------------------------------------------------------------------------- 关注我&#x1f308;&#xff0c;每天更新总结文章…...

基于深度学习的电力负荷预测研究

一、深度学习模型框架 在当今数字化时代&#xff0c;基于深度学习的电力负荷预测研究正成为保障电力系统稳定、高效运行的关键领域。其模型构建是一个复杂而精妙的过程&#xff0c;涉及多学科知识与前沿技术的融合应用。首先&#xff0c;要明确电力负荷预测的目标&#xff0c;…...

篇章十 消息持久化(二)

目录 1.消息持久化-创建MessageFileManger类 1.1 创建一个类 1.2 创建关于路径的方法 1.3 定义内部类 1.4 实现消息统计文件读写 1.5 实现创建消息目录和文件 1.6 实现删除消息目录和文件 1.7 实现消息序列化 1. 消息序列化的一些概念&#xff1a; 2. 方案选择&#xf…...

【IDEA】删除/替换文件中所有包含某个字符串的行

目录 前言 正则表达式 示例 使用方法 前言 在日常开发中&#xff0c;频繁地删除无用代码或清理空行是不可避免的操作。许多开发者希望找到一种高效的方式&#xff0c;避免手动选中代码再删除的繁琐过程。 使用正则表达式是处理字符串的一个非常有效的方法。 正则表达式 …...

基于深度学习的不良驾驶行为为识别检测

一.研究目的 随着全球汽车保有量持续增长&#xff0c;交通安全问题日益严峻&#xff0c;由不良驾驶行为&#xff08;如疲劳驾驶、接打电话、急加速/急刹车等&#xff09;引发的交通事故频发&#xff0c;不仅威胁生命财产安全&#xff0c;还加剧交通拥堵与环境污染。传统识别方…...

FD+Mysql的Insert时的字段赋值乱码问题

方法一 FDQuery4.SQL.Text : INSERT INTO 信息表 (中心, 分组) values(:中心,:分组); FDQuery4.Params[0].DataType : ftWideString; //必须加这个数据类型的定义&#xff0c;否则会有乱码 FDQuery4.Params[1].DataType : ftWideString; //ftstring就不行&#xff0c;必须是…...

第十周作业

一、CSRF 1、DVWA-High等级 2、使用Burp生成CSRF利用POC并实现攻击 二、SSRF&#xff1a;file_get_content实验&#xff0c;要求获取ssrf.php的源码 三、RCE 1、 ThinkPHP 2、 Weblogic 3、Shiro...

Python操作PDF书签详解 - 添加、修改、提取和删除

目录 简介 使用工具 Python 向 PDF 添加书签 添加书签 添加嵌套书签 Python 修改 PDF 书签 Python 展开或折叠 PDF 书签 Python 提取 PDF 书签 Python 删除 PDF 书签 简介 PDF 书签是 PDF 文件中的导航工具&#xff0c;通常包含一个标题和一个跳转位置&#xff08;如…...

One-shot和Zero-shot的区别以及使用场景

Zero-shot是模型在没有任务相关训练数据的情况下进行预测&#xff0c;依赖预训练知识。 One-shot则是提供一个示例&#xff0c;帮助模型理解任务。两者的核心区别在于是否提供示例&#xff0c;以及模型如何利用这些信息。 在机器学习和自然语言处理中&#xff0c;Zero-Shot 和…...

微软 Build 2025:开启 AI 智能体时代的产业革命

在 2025 年 5 月 19 日的微软 Build 开发者大会上&#xff0c;萨提亚・纳德拉以 "我们已进入 AI 智能体时代" 的宣言&#xff0c;正式拉开了人工智能发展的新纪元。这场汇聚了奥特曼、黄仁勋、马斯克三位科技领袖的盛会&#xff0c;不仅发布了 50 余项创新产品&#…...

集星獭 | 重塑集成体验:新版编排重构仿真电商订单数据入库

概要介绍 新版服务编排以可视化模式驱动电商订单入库流程升级&#xff0c;实现订单、客户、库存、发票、发货等环节的自动化处理。流程中通过循环节点、判断逻辑与数据查询的编排&#xff0c;完成了低代码构建业务逻辑&#xff0c;极大提升订单处理效率与业务响应速度。 背景…...

多模态大语言模型arxiv论文略读(八十八)

MammothModa: Multi-Modal Large Language Model ➡️ 论文标题&#xff1a;MammothModa: Multi-Modal Large Language Model ➡️ 论文作者&#xff1a;Qi She, Junwen Pan, Xin Wan, Rui Zhang, Dawei Lu, Kai Huang ➡️ 研究机构: ByteDance, Beijing, China ➡️ 问题背景…...

创建Workforce

创建你的Workforce 3.3.1 简单实践 1. 创建 Workforce 实例 想要使用 Workforce&#xff0c;首先需要创建一个 Workforce 实例。下面是最简单的示例&#xff1a; from camel.agents import ChatAgent from camel.models import ModelFactory from camel.types import Model…...

Cribl 中 Parser 扮演着重要的角色 + 例子

先看文档: Parser | Cribl Docs Parser The Parser Function can be used to extract fields out of events or reserialize (rewrite) events with a subset of fields. Reserialization will preserve the format of the events. For example, if an event contains comma…...

WebSocket 从入门到进阶实战

好记忆不如烂笔头&#xff0c;能记下点东西&#xff0c;就记下点&#xff0c;有时间拿出来看看&#xff0c;也会发觉不一样的感受. 聊天系统是WebSocket的最佳实践&#xff0c;以下是使用WebSocket技术实现的一个聊天系统的关键代码&#xff0c;可以通过这些关键代码&#xff…...

CSS:vertical-align用法以及布局小案例(较难)

文章目录 一、vertical-align说明二、布局案例 一、vertical-align说明 上面的文字介绍&#xff0c;估计大家也看不懂 二、布局案例...

Linux 正则表达式 扩展正则表达式 gawk

什么是正则表达式 正则表达式是我们所定义的模式模板&#xff08;pattern template&#xff09;&#xff0c;Linux工具用它来过滤文本。Linux工具&#xff08;比如sed编辑器或gawk程序&#xff09;能够在处理数据时&#xff0c;使用正则表达式对数据进行模式匹配。如果数据匹配…...

Java转Go日记(五十四):gin路由

1. 基本路由 gin 框架中采用的路由库是基于httprouter做的 地址为&#xff1a;https://github.com/julienschmidt/httprouter package mainimport ("net/http""github.com/gin-gonic/gin" )func main() {r : gin.Default()r.GET("/", func(c …...

【解决】自己的域名任何端口都访问不到,公网地址正常访问,服务器报错500。

一、问题描述 后端项目部署在服务器上&#xff0c;通过域名访问接口服务器报错500&#xff0c;通过浏览器访问域名的任何端口都是无法访问此网站。 但是通过公网地址访问是可以正常访问到的&#xff0c;感觉是域名出现了问题 二、解决过程 先说结论&#xff1a;问题原因是…...

探秘鸿蒙 HarmonyOS NEXT:Navigation 组件的全面解析

鸿蒙 ArkTS 语言中 Navigation 组件的全面解析 一、引言 本文章基于HarmonyOS NEXT操作系统&#xff0c;API12以上的版本。 在鸿蒙应用开发中&#xff0c;ArkTS 作为一种简洁、高效的开发语言&#xff0c;为开发者提供了丰富的组件库。其中&#xff0c;Navigation 组件在构建…...

订单导入(常见问题和sql)

1.印章取行,有几行取几行 union select PARAM07 name, case when regexp_count(PO_PARAM_20, chr(10)) > 0 then substr(PO_PARAM_20, 0, instr(PO_PARAM_20, chr(10)) - 1) else PO_PARAM_20 end value,PO_ID …...

PyTorch中diag_embed和transpose函数使用详解

torch.diag_embed 是 PyTorch 中用于将一个向量&#xff08;或批量向量&#xff09;**嵌入为对角矩阵&#xff08;或批量对角矩阵&#xff09;**的函数。它常用于图神经网络&#xff08;GNN&#xff09;或线性代数中生成对角矩阵。 函数原型 torch.diag_embed(input, offset0,…...

算法分析与设计实验:找零钱问题的贪心算法与动态规划解决方案

在计算机科学中&#xff0c;贪心算法和动态规划是两种常用的算法设计策略。本文将通过一个经典的找零钱问题&#xff0c;详细讲解这两种算法的实现和应用。我们将会提供完整的C代码&#xff0c;并对代码进行详细解释&#xff0c;帮助读者更好地理解和掌握这两种算法。 问题描述…...

制作 MacOS系统 の Heic动态壁纸

了解动态桌面壁纸 当macOS 10.14发布后&#xff0c;会发现系统带有动态桌面壁纸&#xff0c;设置后&#xff0c;我们的桌面背景将随着一天从早上、到下午、再到晚上的推移而发生微妙的变化。 虽然有些软件也有类似的动态变化效果&#xff0c;但是在新系统中默认的HEIC格式的动…...

大数据 笔记

kafka kafka作为消息队列为什么发送和消费消息这么快&#xff1f; 消息分区&#xff1a;不受单台服务器的限制&#xff0c;可以不受限的处理更多的数据顺序读写&#xff1a;磁盘顺序读写&#xff0c;提升读写效率页缓存&#xff1a;把磁盘中的数据缓存到内存中&#xff0c;把…...

js中encodeURIComponent函数使用场景

encodeURIComponent 是 JavaScript 中的一个内置函数&#xff0c;它的作用是&#xff1a; 将字符串编码为可以安全放入 URL 的形式。 ✅ 为什么需要它&#xff1f; URL 中有一些字符是有特殊意义的&#xff0c;比如&#xff1a; ? 用来开始查询参数 & 分隔多个参数 连接…...