截至目前,这是我的代码:
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
scn.Open();
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
CAST(REPLACE(CreditRequest, ',', '') as int)
FROM CreditRequests Where Username=@Username;
SELECT CreditRequest FROM UserData
WHERE Username=@Username", scn);
cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Session["New"];
object value = cmd.ExecuteScalar();
if (value != null)
txtCredit.Text = value.ToString();
}
}
}
但是,当我查看我的数据库时,信用请求值正在插入数据库并生成新的ID,所有内容都是NULL
。
实施例
ID NULL Username NULL Email NULL Contact NULL Creditrequest 5,000
有没有办法将信用申请值插入正确的用户名。我的代码中缺少什么?
另外,我希望在我的文本框中显示该信用请求值,我相信它的这行代码?
if (value != null)
txtCredit.Text = value.ToString();
答案 0 :(得分:1)
您正在调用添加新记录的INSERT语句。不,在最后添加WHERE子句不会在update语句中转换insert语句。
如果您想更新现有记录,请致电
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
(SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
FROM CreditRequests c Where c.Username=@Username)", scn);
对于问题的第二部分,无法在此上下文中获取ExecuteScalar的返回值,因为UPDATE不会选择任何要返回的记录。如果你想获得这个值,你可以发出两个语句,用分号分隔它们:
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
(SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
FROM CreditRequests c Where c.Username=@Username);
SELECT CreditRequest FROM UserData u
WHERE u.Username=@Username", scn);
两个语句都将被执行,但ExecuteScalar将能够返回更新的CreditRequest