页面 *.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) );