一个参数的执行:
string sqlstr = "select count(*) from Users where UserName = @Username";
//打开数据库连接
conn.Open();
//创建命令对象
SqlCommand cmd = new SqlCommand(sqlstr, conn);
//判断SqlCommand对象的ExecuteScalar方法返回的参数是否大于0,大于0说明用户已经存在
cmd.Parameters.AddWithValue("@Username", username);
多个参数的执行:
//string sql = "insert into Users(UserName,UserSex,Password,Email,PassQuestion,PassAnswer) values( '" + userName + "','" + Sex + "','" + passWord + "','" + emailAddress + "','" + tishiQuesetion + "','" + tishiPassWord + "')";
string sql ="insert into Users(UserName,UserSex,Password,Email,PassQuestion,PassAnswer) values(@username,@usersex,@password,@email,@passQuestion,@passAnswer)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@username", userName);
cmd.Parameters.AddWithValue("@usersex", Sex);
cmd.Parameters.AddWithValue("@password", passWord);
cmd.Parameters.AddWithValue("@email", emailAddress);
cmd.Parameters.AddWithValue("@passQuestion", tishiQuesetion);
cmd.Parameters.AddWithValue("@passAnswer", tishiPassWord);
if (Convert.ToInt32(cmd.ExecuteNonQuery()) > 0)
{
Response.Write("<script>alert('恭喜你注册成功!')</script>");
}
else
{
Response.Write("<script>alert('注册失败!')</script>");
}
conn.Close();
}