且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从ASP.NET WebPage更新SQL Server数据库

更新时间:2022-11-25 13:10:07

嗨Saksham

你应该考虑熟悉实体框架,但如果你想快速简单地实现更新:



Hi Saksham
You should consider familiarizing yourself with entity framework, but if you want to achieve just an update fast and easy:

using System.Data.SqlClient; 

protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString = "blablawhichconnectstomyddatabase";
            string sql = "update tbl_x set MyColumn = '{0}' where MyId = {1}";
            int idKey = 1;
            sql = string.Format(sql, "myvalue", idKey);

            using (var cn = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand(sql, cn);
                cmd.ExecuteNonQuery();
            }
}





请将tbl_x替换为您的表名,将MyColumn替换为您的列,将MyId替换为您的主要名称表ID值。



有许多花哨的方法可以完成任务,但只是一个简单的更新,请注意字符串引用和简单数据时的非引用类似于MyId。



或者你可以使用对象数据源,如果你喜欢指南和wysiwyg的 http://msdn.microsoft.com/en-us/library/aa581783.aspx [ ^ ]


有没有捷径。尝试花一些时间阅读这篇全面的文章:插入,更新,在ASP.NET Gridview中删除,将DataSource删除为SQL Server,MS Access(mdb / accdb),XML和Framework为2.0 / 3.0 / 3.5 / 4.0(VS 2005/2008/2010) [ ^ ]
There is no easy way out. Try to spend some time go through this comprehensive article: Insert, Update, Delete in ASP.NET Gridview, DataSource as SQL Server, MS Access (mdb/accdb), XML and Framework as 2.0 / 3.0 / 3.5 / 4.0 (VS 2005/2008/2010)[^]


最简单的方法是使用存储程序 [ ^ ]。



怎么样?请参阅:

如何:执行返回行的存储过程 [ ^ ]

如何:执行返回单个值的存储过程 [ ^ ]

如何:执行不返回值的存储过程 [ ^ ]

如何:为命令对象设置和获取参数 [ ^ ]



注意: 应保护ASP.NET站点免受 SQL注入 [ ^ ]。

如何:防止ASP.NET中的SQL注入 [ ^ ]

在停止之前停止SQL注入攻击您 [ ^ ]

SQL注入及其如何避免 [ ^ ]
The easiest way is to use stored procedures[^].

How? Please see:
How to: Execute a Stored Procedure that Returns Rows[^]
How to: Execute a Stored Procedure that Returns a Single Value[^]
How to: Execute a Stored Procedure that Returns No Value[^]
How to: Set and Get Parameters for Command Objects[^]

NOTE: ASP.NET sites should be protected from SQL Injection[^].
How To: Protect From SQL Injection in ASP.NET[^]
Stop SQL Injection Attacks Before They Stop You[^]
SQL Injection and how to avoid it[^]