C#连接数据库 用户登录

来源:互联网 发布:知秋的小说 太惨 编辑:程序博客网 时间:2024/05/17 00:57

方法1:

string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();   

 SqlConnection conn = new SqlConnection();   

 conn.ConnectionString = connStr;   

 conn.Open();   

 string sql = "select * from admin where username='" + u1 + "' and password='" + p1 + "'";   

 SqlCommand cmd = new SqlCommand(sql, conn);   

 bool bl = cmd.ExecuteScalar() == null ? true : false;   

 conn.Close();   

 if (bl == false) Response.Write("登录成功!");   

 else Response.Write("登录失败");  

方法2:

string sql = "server=localhost;database=test;uid=sa;pwd=123456";   

SqlConnection con = new SqlConnection(sql); //连接数据库    

// SqlDataAdapter oda = new SqlDataAdapter("select * from where text_No='" + TextBox1.Text + "'and pwd='" + TextBox2.Text + "'",con);   

//构造SQL语句,该语句在RegUsers表中检查昵称和密码是否正确    

string str = "select * from admin where username='" + u1 + "'and password='" + p1 + "'";   

con.Open(); //   打开连接   

SqlCommand cmd = new SqlCommand(str, con);  //   创建Command对象    

SqlDataReader dr = cmd.ExecuteReader(); //   执行ExecuteReader()方法   

if (dr.Read())   

{   

    //Response.Redirect("text2.aspx");   

    Response.Write("登录成功!");   

}   

else  

{   

    Response.Write("登录失败");   

}   

dr.Close();   

con.Close();  

原创粉丝点击