更新表 SQL 查询:SqlConnection
Posted
技术标签:
【中文标题】更新表 SQL 查询:SqlConnection【英文标题】:Update Table SQL Query: 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...? 【参考方案1】:你追求的是这样的:
await sqlConnection.ExecuteAsync(@"
UPDATE Customer
SET Name = @name, Address = @address,
PostalCode = @postalCode, City = @city
WHERE CustomerId=@customerId",
new customerId, name, address, postalCode, city );
但是,我不知道您打算从哪里获得 name
、address
等 - 它们没有显示在问题中。
【讨论】:
【参考方案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
);
【讨论】:
以上是关于更新表 SQL 查询:SqlConnection的主要内容,如果未能解决你的问题,请参考以下文章