c#实现简单的用户注册,判断用户名是否重复

Button1点击事件 //用户注册{SQL查询yonghu表里的uid字段是否与TextBox1相同if(相同的条数>0) //这里是关键,不知道这应该怎么写{提示:注册用户名重复}else{执行添加用户名,密码登陆,返回主页。}}这是一个简单的流程。SQL查询yonghu表里的uid字段是否与TextBox1相同if(相同的条数>0)请把这两段翻译成完整的代码。 能直接用,谢谢了!在线等候,谢谢。
2026-12-04 03:55:14
推荐回答(3个)
回答1:

SqlConnection con = new SqlConnection("");//括号里面写上连接字符串
con.Open();
string sql ="select count(*) from yonghu where uid="+int.Parse(this.TextBox1.Text);//uid是什么类型,假设为整形,如果是字符串加单引号
SqlCommand cmd = new SqlCommand(sql,con);
int row = (int32)cmd.ExecuteScalar()//row大于等于1,有重复结构

回答2:

SQL查询yonghu表里的uid字段是否与TextBox1相同

String.Format("select uid from yonghu where uid={0}",TextBox1.Text)

这里一般使用参数化查询,防止SQL诸如攻击,但就你目前水平,以上语句足矣

if(相同的条数>0)

if(cmd.ExecuteScalar>0)
{

}

回答3:

protected void Button1_Click(object sender, EventArgs e)
{
//查找是否有重复用户名
List models = BLLServices.Yonghu.GetList(TextBox1.Text.Trim());
if(models != null && models.Count > 0){
lbl_UID_tips.Text = "注册用户名重复";
return;
}
//添加用户名或密码
Model.Yonghu model = new Model.Yonghu();
model.Uid = TextBox1.Text.Trim();
model.Pass = TextBox2.Text.Trim();
BLLServices.Yonghu.Insert(model);
//用户登录
if(BLLServices.Yonghu.UserLogin(TextBox1.Text.Trim(),TextBox2.Text.Trim())){
lbl_LOGIN_tips.Text = "登录失败,请核对用户名或密码";
return;
}
Response.Redirect("~/",True); //登录成功,返回主页
}