C# 单击BTN后更新sql表值
我有一张桌子,上面有一些物品:C# 单击BTN后更新sql表值,c#,asp.net,sql-server,linq-to-sql,onclick,C#,Asp.net,Sql Server,Linq To Sql,Onclick,我有一张桌子,上面有一些物品: id | title | ordersTillNow 我想在button click事件中编写c#代码,以便客户单击purchase按钮后,ordersTillNow列将增加一(++) 使用LINQtoSQL可以做到这一点吗?还是使用SqlCommand 无论如何,我如何在c#(代码隐藏,使用Linq to SQL或SqlCommand)上实现这一点?假设您使用的是Linq to SQL,那么您的数据库将有一个数据上下文和一个表示表的对象 当客户点击时,您会编写
id | title | ordersTillNow
我想在button click事件中编写c#代码,以便客户单击purchase按钮后,ordersTillNow
列将增加一(++)
使用LINQtoSQL可以做到这一点吗?还是使用SqlCommand
无论如何,我如何在c#(代码隐藏,使用Linq to SQL或SqlCommand)上实现这一点?假设您使用的是Linq to SQL,那么您的数据库将有一个数据上下文和一个表示表的对象 当客户点击时,您会编写如下代码:
using (YourDataContext ctx = new YourDataContext())
{
Customer myCust = from c in ctx.Customers
where c.CustomerId == ID
select c;
myCust.ordersTillNow++;
ctx.SubmitChanges()
}
string updateStmt = "UPDATE dbo.YourTable SET ordersTillNow = ordersTillNow + 1 " +
"WHERE CustomerID = @CustomerID";
using(SqlConnection _conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand(_conn, updateStmt))
{
_cmd.Parameters.Add("@CustomerID", SqlDbType.Int).Value = yourCustomerID;
_conn.Open();
_cmd.ExecuteNonQuery();
_conn.Close();
}
使用SqlCommand
,您有很多选项可以执行此操作—存储过程、内联SQL—无论什么
您将编写如下代码:
using (YourDataContext ctx = new YourDataContext())
{
Customer myCust = from c in ctx.Customers
where c.CustomerId == ID
select c;
myCust.ordersTillNow++;
ctx.SubmitChanges()
}
string updateStmt = "UPDATE dbo.YourTable SET ordersTillNow = ordersTillNow + 1 " +
"WHERE CustomerID = @CustomerID";
using(SqlConnection _conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand(_conn, updateStmt))
{
_cmd.Parameters.Add("@CustomerID", SqlDbType.Int).Value = yourCustomerID;
_conn.Open();
_cmd.ExecuteNonQuery();
_conn.Close();
}
在发布问题之前,你是否尝试过谷歌搜索?