【问题标题】:Update Table SQL Query: SqlConnection更新表 SQL 查询:SqlConnection
【发布时间】:2020-08-04 11:30:36
【问题描述】:

我想根据 Id 参数更新记录,我尝试了以下步骤,但这似乎不正确,因为它会产生编译错误:

public async Task CustomerUpdateAsync(string customerId)
{
  await using var sqlConnection = new SqlConnection(_connectionString);
            {
                var sqlQuery = "UPDATE Customer(CustomerId,Name,Address,PostalCode,City)" +
                          "SET (@CustomerId,@Name,@Address,@PostalCode,@City)" +
                          $"WHERE CustomerId=@CustomerId", new {CustomerId = customerId};

                await sqlConnection.ExecuteAsync(sqlQuery, customerId);
            }
}

错误:

只有赋值调用递增递减等待和新对象表达式可以作为语句使用

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题:mysql、sql-server、oracle...?

标签: c# sql asp.net-core dapper sqlclient


【解决方案1】:

你追求的是这样的:

await sqlConnection.ExecuteAsync(@"
UPDATE Customer
SET    Name = @name, Address = @address,
       PostalCode = @postalCode, City = @city
WHERE  CustomerId=@customerId",
     new { customerId, name, address, postalCode, city });

但是,我不知道您打算从哪里获得 nameaddress 等 - 它们没有显示在问题中。

【讨论】:

    【解决方案2】:

    谢谢大家,我稍微调整一下就解决了:-

     public async Task CustomerUpdateAsync(Customer customer)
                {
                    await using var sqlConnection = new SqlConnection(_connectionString);
                    {
                        var sql = "UPDATE Customer SET Name=@Name,Address=@Address, PostalCode=@PostalCode," +
                                  "City=@City WHERE CustomerId=@CustomerId";
                        await sqlConnection.ExecuteAsync(sql, new
                        {
                           CustomerId = customer.CustomerId,
                           Name = customer.Name,
                           Address = customer.Address,
                           PostalCode = customer.PostalCode,
                           City = customer.City
                        });
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 2022-01-08
      相关资源
      最近更新 更多