同时将记录插入到SQL Server数据库表单中的asp.net web表单中插入两次

时间:2016-12-20 19:37:12

标签: c# asp.net sql-server

我正在将值插入到Web表单中并提交Web表单。该记录在我的SQL Server 2014数据库中插入两次。我的网络表单代码和逻辑背后的代码如下。

我不知道为什么要将记录两次插入数据库。

网络表单代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="register.aspx.cs" Inherits="register" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Social Login Form Flat Responsive widget Template :: w3layouts</title>
</head>
<body>

<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Social Login Form Widget Responsive, Login form web template,Flat Pricing tables,Flat Drop downs  Sign up Web Templates, Flat Web Templates, Login signup Responsive web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- font files  -->
<link href='/../fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
<link href='/../fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'>
<!-- /font files  -->
<!-- css files -->
<link href="login.css" rel='stylesheet' type='text/css' media="all" />
<!-- /css files -->
</head>
<body>
<h1>Social Login Form</h1>
<div class="log">
    <div class="social w3ls">
        <li class="f"><a href="#"><img src="images/fb.png" alt=""></a></li>
        <li class="t"><a href="#"><img src="images/twt.png" alt=""></a></li>
        <li class="p"><a href="#"><img src="images/pin.png" alt=""></a></li>
        <li class="i"><a href="#"><img src="images/ins.png" alt=""></a></li>
        <div class="clear"></div>
    </div>
    <div class="content2 w3agile">
        <h2>Sign Up</h2>
        <form ID="form" runat="server" method="post"> 

        <asp:TextBox ID="name" runat="server" placeholder="Name Surname"  pattern="[A-Za-z]+\s[A-Za-z]+" title="Firstname Surname" required></asp:TextBox>
        <asp:TextBox ID="username" runat="server" placeholder="Username"  title="Username" required></asp:TextBox>
        <asp:TextBox ID="phoneno" runat="server"  placeholder="Phone Number"  pattern="[7-9]{1}[0-9]{9}" required title="Phone number starting with 7-9 and remaing 9 digit with 0-9"></asp:TextBox>    
        <asp:TextBox ID="email" type="email" runat="server" placeholder="Email Address"  required ></asp:TextBox>
        <asp:TextBox ID="password" runat="server" type="password"  placeholder="Password"  required title="Any number of characters or special characters"></asp:TextBox>
        <input id="confirm_password" placeholder="Confirm Password" runat="server" type="password"  required title="Any number of characters or special characters"></input>

            <script type="text/javascript">
                var password = document.getElementById("password")
  , confirm_password = document.getElementById("confirm_password");

                function validatePassword() {
                    if (password.value != confirm_password.value) {
                        confirm_password.setCustomValidity("Passwords Don't Match");
                    } else {
                        confirm_password.setCustomValidity('');
                    }
                }

                password.onchange = validatePassword;
                confirm_password.onkeyup = validatePassword;
            </script>


        <asp:Button ID="Button1" runat="server" Text="Sign up" class="register" OnClick="btn_Click" />
            <h3>Already have an account? <a href="login.aspx">Sign In</a></h3>
    </div>
</div>
<div class="footer">
    <p>© 2016 Social Login Form. All Rights Reserved | Design by <a href="https://w3layouts.com/" target="_blank">w3layouts</a></p>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
        </form>
</body>
</html>

代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        int userId = 0;

        SqlConnection con = new SqlConnection(@"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");

        String query = "Insert into Table_2 values('"+name.Text+"','"+username.Text+"','"+phoneno.Text+"','"+email.Text+"','"+password.Text+"')";

        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        userId = Convert.ToInt32(cmd.ExecuteScalar());

        cmd.ExecuteNonQuery();
        //Label1.Text = "Hjg";
        con.Close();
    }
}

2 个答案:

答案 0 :(得分:5)

这一行

userId = Convert.ToInt32(cmd.ExecuteScalar());

没有按你的想法行事。它将执行insert语句,然后返回标量值。

然后你的下一行:

cmd.ExecuteNonQuery();

将再次插入记录

这是Blorgbeard试图告诉你的。

这就是它插入两次的原因。

也 - 您应该考虑参数化该查询。获取用户输入的值并使用这些值创建查询而不检查它们只是求助于SQL注入攻击

答案 1 :(得分:4)

使用参数化查询,类似....

int userId = 0;
SqlConnection con = new SqlConnection(@"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");

SqlCommand cmd = new SqlCommand("Insert into Table_2 values(@Name, @UserName, @Phone, @Email, @Password); 
                                        SELECT CAST(scope_identity() AS int)", con);

cmd.Parameters.AddWithValue("@Name", name.Text);
cmd.Parameters.AddWithValue("@UserName", username.Text);
cmd.Parameters.AddWithValue("@Phone", phoneno.Text);
cmd.Parameters.AddWithValue("@Email", email.Text);
cmd.Parameters.AddWithValue("@Password", password.Text);

con.Open();

userId = (Int)cmd.ExecuteScalar();