You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现Price与Quantity相乘并写入数据库Total字段?

在C#中实现Price与Quantity相乘并写入Total字段

方式一:使用ADO.NET(原生数据库操作)

适合需要直接控制SQL语句的场景,以SQL Server为例:

using System.Data.SqlClient;

// 替换为你的数据库连接字符串
string connectionString = "Server=你的服务器地址;Database=目标数据库名;Integrated Security=True;";
int targetRecordId = 1; // 要更新的记录ID
decimal price = 99.9m;
int quantity = 5;
decimal total = price * quantity;

using (SqlConnection connection = new SqlConnection(connectionString))
{
    // 更新已有记录的Total字段,假设表名为Order,主键为Id
    string updateSql = "UPDATE [Order] SET Total = @Total WHERE Id = @Id";
    
    using (SqlCommand command = new SqlCommand(updateSql, connection))
    {
        // 添加参数防止SQL注入
        command.Parameters.AddWithValue("@Total", total);
        command.Parameters.AddWithValue("@Id", targetRecordId);
        
        connection.Open();
        int affectedRows = command.ExecuteNonQuery();
        // 可通过affectedRows判断是否成功更新记录
    }
}

如果是新增记录时直接计算Total,修改SQL为INSERT即可:

string insertSql = "INSERT INTO [Order] (Price, Quantity, Total) VALUES (@Price, @Quantity, @Total)";
command.Parameters.AddWithValue("@Price", price);
command.Parameters.AddWithValue("@Quantity", quantity);
command.Parameters.AddWithValue("@Total", total);

方式二:使用Entity Framework Core(ORM框架)

如果项目使用EF Core,代码更简洁,无需手动编写SQL:

首先定义对应数据库表的实体类:

public class Order
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public decimal Total { get; set; }
}

配置DbContext:

public class AppDbContext : DbContext
{
    public DbSet<Order> Orders { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("你的数据库连接字符串");
    }
}

执行更新或新增操作:

using (var context = new AppDbContext())
{
    // 更新已有记录
    var targetOrder = context.Orders.FirstOrDefault(o => o.Id == targetRecordId);
    if (targetOrder != null)
    {
        targetOrder.Total = targetOrder.Price * targetOrder.Quantity;
        context.SaveChanges();
    }

    // 新增记录
    var newOrder = new Order
    {
        Price = 99.9m,
        Quantity = 5,
        Total = 99.9m * 5
    };
    context.Orders.Add(newOrder);
    context.SaveChanges();
}

注意事项

  • 优先用decimal类型存储Price和Total,避免float/double类型的精度丢失问题。
  • 必须使用参数化操作(ADO.NET的参数或EF Core自动参数化),防止SQL注入。
  • 建议添加try-catch块捕获数据库连接失败、操作超时等异常。

内容的提问来源于stack exchange,提问作者John Cloed Guarra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:10:30