【问题标题】:Double data insert into database asp.net c#双数据插入数据库asp.net c#
【发布时间】:2016-11-07 14:02:55
【问题描述】:

我正在做航空公司预订系统。当我将所有数据插入数据库时​​,它会插入双数据。为什么会这样? 这是我的代码:

public partial class CompleteOrder : System.Web.UI.Page
{
    string SeatNum;
protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-28L03QE\SQL2014;Initial Catalog=Airline;Integrated Security=True;Pooling=False");
    con.Open();

    Random rnd = new Random();
    int ordernum = rnd.Next(3, 10000);
    string Name = Request.QueryString["name"];
    string IC = Request.QueryString["ic"];
    string Contact = Request.QueryString["contact"];
    string SeatType = (string) (Session["seats"]);
    SeatNum = Request.QueryString["seatnum"];

    Label7.Text = Convert.ToString(ordernum);
    Label4.Text = Name;
    Label8.Text = IC;
    Label10.Text = Contact;
    Label14.Text = SeatType;
    Label16.Text = SeatNum;



    SqlCommand cmd = new SqlCommand("INSERT INTO [Table](OrderNum,Name,IdentificationNumber, ContactNumber, SeatType, SeatNumber)VALUES('" + Label7.Text + "','" + Label4.Text + "','" + Label8.Text + "','" + Label10.Text + "', '" + Label14.Text + "', '" + Label16.Text + "')", con);
    cmd.ExecuteNonQuery();
    con.Close();
}

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    Response.Redirect("~/Main.aspx?seatnum="+SeatNum);
}
}

请帮帮我,谢谢。

【问题讨论】:

  • 我认为没有。 @Jonesopolis
  • Visual Studio 中有一个调试菜单是有原因的。

标签: c# asp.net


【解决方案1】:

可能是点击图片按钮后。因为第一个数据是在页面加载时插入的,第二个数据是在由于单击图像按钮而发生回发之后插入的。您可以通过将插入逻辑保留在内部来避免这种情况

if(!Page.IsPostBack)
{
    // insert code
}

我仍然很困惑为什么您在页面加载时插入数据。有人可以把你的数据库填得太多而惹恼你。

【讨论】:

  • 因为我想显示用户在上一页填写的信息,所以我直接将值传递给页面加载。
  • 可以先保存值再重定向。
【解决方案2】:

这里有两个不好的做法。

首先,您应该使用 sql 参数而不是简单地连接它们;避免 SQL 注入。阅读here

其次,不要在 HTTP GET (Page_Load) 中进行插入。您应该在 HTTP POST 中执行此操作,然后再次重定向到 HTTP GET(PRG 模式)。

双重插入的原因可能是因为你两次点击了同一个页面(本例中为Page_Load);如果您应用 PRG 模式,您会注意到一些事情。

Post-Redirect-Get with ASP.NET

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    相关资源
    最近更新 更多