ASP.NET 修改数据库数据

在 ASP.NET 中,修改数据库数据是一个常见的任务,本文将详细讲解如何在 ASP.NET 中通过 C# 代码实现对数据库数据的修改,我们将使用 ADO.NET 来与数据库进行交互,以下是步骤和示例代码:
准备工作
确保你已经安装了 .NET SDK 和一个支持的数据库(如 SQL Server),你还需要安装相应的 NuGet 包,例如System.Data.SqlClient。
创建数据库和表
假设我们有一个名为Products 的数据库和一个名为Product 的表,其结构如下:
CREATE DATABASE Products;
GO
USE Products;
GO
CREATE TABLE Product (
ProductID INT PRIMARY KEY,
ProductName NVARCHAR(50),
Price DECIMAL(10, 2)
);
3. 创建 ASP.NET Web 应用程序
打开 Visual Studio,创建一个新的 ASP.NET Web 应用程序项目,选择 Web Forms 模板(或者你也可以使用 MVC、Razor Pages等)。
配置连接字符串
在Web.config 文件中添加数据库连接字符串:

<connectionStrings>
<add name="DefaultConnection" connectionString="Server=your_server_name;Database=Products;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
编写修改数据的方法
在代码隐藏文件(如Default.aspx.cs)中,编写一个方法来更新数据库中的数据:
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 确保页面不是回发请求
if (!IsPostBack)
{
BindGrid(); // 绑定初始数据到网格视图
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Product"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
int productId = int.Parse(ProductIDTextBox.Text);
decimal newPrice = decimal.Parse(NewPriceTextBox.Text);
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Product SET Price = @Price WHERE ProductID = @ProductID", con))
{
cmd.Parameters.AddWithValue("@Price", newPrice);
cmd.Parameters.AddWithValue("@ProductID", productId);
cmd.ExecuteNonQuery();
}
con.Close();
}
BindGrid(); // 重新绑定数据以显示更新后的结果
}
}
}
设计前端界面
在Default.aspx 文件中,添加必要的控件来输入产品 ID 和新的价格,以及一个按钮来触发更新操作:
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<title>ASP.NET Update Database Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Update Product Price</h2>
<table>
<tr>
<td>Product ID:</td>
<td><asp:TextBox ID="ProductIDTextBox" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>New Price:</td>
<td><asp:TextBox ID="NewPriceTextBox" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="UpdateButton" runat="server" Text="Update" OnClick="UpdateButton_Click" /></td>
</tr>
</table>
</div>
<br />
<h2>Product List</h2>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"></asp:GridView>
</form>
</body>
</html>
运行应用程序
按下 F5 键运行应用程序,输入产品 ID 和新的价格,然后点击“Update”按钮,如果一切正常,你会看到产品表中的价格被更新了。
相关问答
问题1:如何防止SQL注入攻击?
答:为了防止SQL注入攻击,可以使用参数化查询,在上面的例子中,我们已经使用了参数化查询(cmd.Parameters.AddWithValue),这可以有效地防止SQL注入攻击,确保不要直接将用户输入拼接到SQL语句中。

问题2:如何捕获和处理异常?
答:在执行数据库操作时,可能会遇到各种异常,如连接失败、命令执行失败等,你可以在try-catch块中捕获这些异常并进行相应的处理。
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Product SET Price = @Price WHERE ProductID = @ProductID", con))
{
cmd.Parameters.AddWithValue("@Price", newPrice);
cmd.Parameters.AddWithValue("@ProductID", productId);
cmd.ExecuteNonQuery();
}
con.Close();
}
catch (SqlException ex)
{
// 处理SQL异常,例如记录日志或显示错误信息给用户
Response.Write("An error occurred while updating the database: " + ex.Message);
}
catch (Exception ex)
{
// 处理其他类型的异常
Response.Write("An unexpected error occurred: " + ex.Message);
}
finally
{
con.Close(); // 确保连接关闭,即使发生异常也不例外
}
以上就是关于“asp.net 修改数据库数据”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!