gpt4 book ai didi

c# - 更新 SQL 语句未触发到数据库

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:30 29 4
gpt4 key购买 nike

我想知道我的代码中缺少什么。我只想从 CreditRequest 表中获取特定值 creditrequest 并将其放入 UserData 表中,creditrequest 列。不知何故,我的代码没有执行任务。

这是我的代码:

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
scn.Open();

SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
(SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
FROM CreditRequests c Where c.Username=@Username", scn);

cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Session["New"];

cmd.ExecuteNonQuery();
}

最佳答案

让我们逐行查看代码。

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
//I hope this is correct. Else "Server=PAOLO;Database=ShoppingCartDB;Integrated Security=True"
{
scn.Open();
/*
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
(SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
FROM CreditRequests c Where c.Username=@Username", scn);
*/
//SQL statement is all wrong and can update all rows
//Correct is
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest = "
+ "CAST(REPLACE(c.CreditRequest, ',', '') as int) "
+ " FROM CreditRequests c inner join UserData u "
+ "on c.Username=u.Username Where c.Username=@Username", scn);
cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = (string)Session["New"]; //This is good

cmd.ExecuteNonQuery();
}

关于c# - 更新 SQL 语句未触发到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558373/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com