c# - 如何将传递的值添加到数据库?
问题描述
我正在用 ASP.NET C# 练习 WebApplication
我已经在该页面中创建了产品页面我已经使用来自数据库的数据创建了 gridview,而且每一行中都有一个名为 Edit 的按钮。它将带您使用该行数据更新页面。它会将值相应地放在文本框中。
更新页面中有文本字段和下拉框,但是当我更改数据并单击更新按钮时,数据库中的数据不会更新。
产品.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5.Product
{
public partial class Product1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string pid = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("UpdateProduct.aspx?Product_ID=" + pid);
}
}
}
更新产品.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
namespace WebApplication5.Product
{
public partial class UpdateProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
String myquery = "Select * from Product where pro_id=" + Request.QueryString["Product_ID"];
SqlConnection con = new SqlConnection(mycon);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtpid.Text = ds.Tables[0].Rows[0]["pro_id"].ToString();
txtpname.Text = ds.Tables[0].Rows[0]["pro_name"].ToString();
txtpprice.Text = ds.Tables[0].Rows[0]["pro_price"].ToString();
txtpq.Text = ds.Tables[0].Rows[0]["pro_qty"].ToString();
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con1.Open();
string sql ="UPDATE Product set pro_name='"+txtpname.Text.ToString()+"',cat_name='"+DropDownList1.SelectedValue.ToString()+"',pro_price='"+txtpprice.ToString()+"',pro_qty='"+txtpq.ToString()+"'where pro_id='"+txtpid.Text.ToString()+"'";
SqlCommand cmd1 = new SqlCommand(sql,con1);
cmd1.ExecuteNonQuery();
Response.Write("Updated!");
}
}
}
解决方案
请使用 SQLcatch(SqlException ex) 进行 try catch 块,并尝试使用属性。您在 MSSQL 中也有很好的工具,它被称为“SQL 服务器分析器”。
推荐阅读
- c# - Windows UIAutomationElement 内存泄漏
- java - 如何在 android.support.design.chip.Chip 中设置文本颜色?
- websocket - 通过 websocket 使用 Broadway.js 和 raspi-camera 的问题
- jenkins - 将 Jenkins 连接到 GCP 容器注册表
- python - 未找到 GraphViz 的可执行文件(python 3 和 pydotplus)
- python - 如何创建具有最小值计数的子 DatafFrame
- java - 具有不同切点的 XGBoost 交叉验证
- amazon-kinesis - 使用 firehose 从 Kinesis 流中消费数据,报告 Kinesis Throttling 错误
- node.js - WinstonJS 将时间戳集成到 FileTransport 的日志文件名中
- machine-learning - RNN:Keras框架中LSTM层的return_sequences有什么用