共同的代码:string uid = txtUser.Text.Trim().ToString();//保存登录界面输入的用户名
string pwd = txtPwd.Text.Trim().ToString();//保存登录界面输入的密码
//string constr = "server=.;database=user;uid=sa;pwd=123456;";
string conStr = ConfigurationManager.ConnectionStrings["connectionString"].ToString();//取出配置文件中连接字符串
SqlConnection conn = new SqlConnection(conStr);
conn.Open();//打开数据库连接
方法一:只使用dataadapter适配器对象
string sql = "select *from admin where userName='" + uid + "' and pwd='" + pwd + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds,"admin");
if (ds.Tables!=null)
{
Session["uid"]=uid;
Session["pwd"]=pwd;
Response.Redirect("index.aspx");
}
else { Response.Write("<script>alert('用户名或密码错误!')</script>"); }
方法二:使用sqlcommand命令中的ExecuteScalar()方法返回结果集中的第一行中的第一列
string sql = "select count(*) from admin where userName='"+uid+"' and pwd='"+pwd+"'";
SqlCommand cmd = new SqlCommand(sql, conn);//构建cmd命令对象
int i =(int)cmd.ExecuteScalar();
if (i>0)
{
Session["uid"]=uid;
Session["pwd"]=pwd;
Response.Redirect("index.aspx");
}
else { Response.Write("<script>alert('用户名或密码错误!')</script>"); }
方法三:使用sqlcommand命令中的ExecuteReader()方法返回SqlDataReader的结果集
string sql = "select *from admin where userName='" + uid + "' and pwd='" + pwd + "'";
SqlDataReader sdr=cmd.ExecuteReader();
sdr.Read();
if (sdr.HasRows)
{
Session["uid"]=uid;
Session["pwd"]=pwd;
Response.Redirect("index.aspx");
}
else { Response.Write("<script>alert('用户名或密码错误!')</script>"); }
string pwd = txtPwd.Text.Trim().ToString();//保存登录界面输入的密码
//string constr = "server=.;database=user;uid=sa;pwd=123456;";
string conStr = ConfigurationManager.ConnectionStrings["connectionString"].ToString();//取出配置文件中连接字符串
SqlConnection conn = new SqlConnection(conStr);
conn.Open();//打开数据库连接
方法一:只使用dataadapter适配器对象
string sql = "select *from admin where userName='" + uid + "' and pwd='" + pwd + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds,"admin");
if (ds.Tables!=null)
{
Session["uid"]=uid;
Session["pwd"]=pwd;
Response.Redirect("index.aspx");
}
else { Response.Write("<script>alert('用户名或密码错误!')</script>"); }
方法二:使用sqlcommand命令中的ExecuteScalar()方法返回结果集中的第一行中的第一列
string sql = "select count(*) from admin where userName='"+uid+"' and pwd='"+pwd+"'";
SqlCommand cmd = new SqlCommand(sql, conn);//构建cmd命令对象
int i =(int)cmd.ExecuteScalar();
if (i>0)
{
Session["uid"]=uid;
Session["pwd"]=pwd;
Response.Redirect("index.aspx");
}
else { Response.Write("<script>alert('用户名或密码错误!')</script>"); }
方法三:使用sqlcommand命令中的ExecuteReader()方法返回SqlDataReader的结果集
string sql = "select *from admin where userName='" + uid + "' and pwd='" + pwd + "'";
SqlDataReader sdr=cmd.ExecuteReader();
sdr.Read();
if (sdr.HasRows)
{
Session["uid"]=uid;
Session["pwd"]=pwd;
Response.Redirect("index.aspx");
}
else { Response.Write("<script>alert('用户名或密码错误!')</script>"); }