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

.NET新手ASP.NET电商项目FactorRepository遇Sql语法错误求助

问题分析:ASP.NET电商应用中FactorRepository的SQL语法错误

你的代码存在多个问题,直接引发了SQL语法报错,下面逐个说明:

1. 字符串拼接SQL引发的语法错误(核心报错原因)

你直接把createdDate这个DateTime变量拼进SQL语句,生成的SQL会变成类似这样:

Insert into Factors (CustomerId, TotalPrice, CreatedDate) values (1, 100, 2024/12/01)

SQL Server会把日期里的/当成除法运算符,自然会报"Incorrect syntax near '12'"的错误。而且这种写法还存在SQL注入风险,绝对不能使用。

2. Insert操作错误使用ExecuteReader

ExecuteReader是用来读取查询结果集的,Insert操作本身没有结果集,应该用ExecuteNonQuery。如果要获取刚插入的Factor信息,需要修改SQL语句,通过OUTPUT子句返回插入的记录。

3. 硬编码覆盖方法参数

方法定义的cartId和customerId参数完全没用到,你直接把它们赋值成1,这会导致方法逻辑完全不符合预期。

4. 手动关闭连接多余

using块会自动管理SqlConnection的生命周期,执行完后会自动关闭并释放连接,不需要手动调用sql.Close()。

5. 异常处理无意义

catch (Exception) { throw; }这种写法完全没用,既没处理异常,也没添加额外信息,不如直接去掉try-catch,让异常向上抛出。


修正后的代码示例

public class FactorRepository : IFactorRepository
{
    private const string _connectionString = "ConnectionString"; // 注意修正拼写错误:ConntectionString → ConnectionString

    private readonly ICartRepository _cartRepository;
    private readonly IProductRepository _productRepository;

    // 用readonly修饰注入的依赖,更符合规范
    public FactorRepository(ICartRepository cartRepository, IProductRepository productRepository)
    {
        _cartRepository = cartRepository;
        _productRepository = productRepository;
    }

    public Factor CreateFactor(int cartId, int customerId)
    {
        var cart = _cartRepository.GetCartBy(cartId); // 使用传入的cartId,而非硬编码1
        int totalPrice = cart.TotalPrice;
        DateTime createdDate = DateTime.Now.Date;

        using (SqlConnection sql = new SqlConnection(_connectionString))
        {
            sql.Open();
            SqlCommand command = sql.CreateCommand();
            command.CommandType = CommandType.Text;
            // 使用参数化查询,避免SQL注入和语法错误,同时用OUTPUT返回插入的记录
            command.CommandText = @"
                INSERT INTO Factors (CustomerId, TotalPrice, CreatedDate)
                OUTPUT INSERTED.CustomerId, INSERTED.TotalPrice, INSERTED.CreatedDate
                VALUES (@CustomerId, @TotalPrice, @CreatedDate)";
            
            // 添加参数
            command.Parameters.AddWithValue("@CustomerId", customerId);
            command.Parameters.AddWithValue("@TotalPrice", totalPrice);
            command.Parameters.AddWithValue("@CreatedDate", createdDate);

            // 读取OUTPUT返回的插入记录
            using (var reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    return new Factor
                    {
                        CustomerId = (int)reader["CustomerId"],
                        TotalPrice = (int)reader["TotalPrice"],
                        CreatedDate = (DateTime)reader["CreatedDate"]
                    };
                }
            }
        }

        return null; // 插入失败时返回null,也可根据业务需求抛出异常
    }
}

另外注意你的连接字符串常量拼写错误:ConntectionString应该是ConnectionString,虽然这不是当前报错的原因,但后续会导致数据库连接失败。


内容的提问来源于stack exchange,提问作者Alireza Alavi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:23:19