使用SqlParameter向数据库中插入数据

页面   *.aspx

<form runat="server" id="form1">
        <div>
            <asp:TextBox ID="txtname" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtpwd" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />

        </div>
</form>


后台代码   *.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
        {

            String strConn = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\guest.mdf;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(strConn))
            {
                con.Open();
                string str = "select count(*) from T where UuName='" + txtname.Text + "'";
                    SqlCommand com = new SqlCommand(str, con);
                    int intcont = Convert.ToInt32(com.ExecuteScalar());
                    if (intcont > 0)//判断数据库中是否有相同的录 
                    {
                        Response.Write("alert('对不起!不允许填写相同记录!')");
                    }
                    else
                    {
                        try
                        {
                            //插入命令 
                            string sqlString = "insert into T(UuName,Ppassword) values(@UuName,@Ppassword)";
                            //创建SqlCommand实例,并设置SQL语句和使用的连接实例
                            SqlCommand mycom = new SqlCommand(sqlString, con);
                            SqlParameter[] tvpParam = new SqlParameter[]
                        {
                            new SqlParameter("@UuName",txtname.Text),
                            new SqlParameter("@Ppassword",txtpwd.Text),
                        };

                            mycom.Parameters.AddRange(tvpParam);
                            mycom.ExecuteNonQuery();
                            Response.Write("good");
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.Message.ToString());
                        }
                    }
            }

数据库

CREATE TABLE [dbo].[T] (
    [Id]        INT           IDENTITY (1, 1) NOT NULL,
    [UuName]    NVARCHAR (50) NULL,
    [Ppassword] NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

 

 

 

转载于:https://www.cnblogs.com/Harry369/archive/2013/05/17/3083651.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值