zoukankan      html  css  js  c++  java
  • 使用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)
    );
  • 相关阅读:
    获取元素js点击tab,input获取当前文本,
    弹框,点击显示和隐藏
    rem单位,10px等于0.1rem,移动端背景自适应
    移动端轮播图效果,插件
    点击显示或隐藏,添加类名或删除类名
    南瓜小园
    焦点图带箭头-插件-26
    返回顶部,右侧浮窗-25
    点击左右箭头轮播-24
    倒计时拉幕广告,对联广告效果-23
  • 原文地址:https://www.cnblogs.com/Harry369/p/3083651.html
Copyright © 2011-2022 走看看