1.建立一个test数据库
2.建立一张testUser表
3.修改sa的密码
4.用sa登陆数据库
5.查询数据库代码
string strCon = "server=.;database=test;user=sa;pwd=123";
void Login()
{
//数据库连接
SqlConnection con = new SqlConnection(strCon);
//con.ConnectionString = strCon;
//sql语句,Connection对象,指令编辑
//"+txtName.Text+"
//string str1 = "1";
//string str2 = "a";
//string str3 = "b" + txtName.Text + txtPwd.Text;
//string strSql = "select * from testUser where testName='" + txtName.Text + "' and testPwd='" + txtPwd.Text + "' ";//该写法不提倡
string strSql = "select * from testUser where testName=@name and testPwd=@pwd ";//先编译再执行,存储过程,一组编译好的sql语句组成
SqlCommand cmd = new SqlCommand(strSql, con);
//Parameters参数集合
cmd.Parameters.Add("@name", SqlDbType.VarChar, 50);
cmd.Parameters["@name"].Value = txtName.Text;
cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 50).Value = txtPwd.Text;
try
{
//con.Open();//打开数据库连接
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
//查询结果存放于DataTable中
sda.Fill(dt);
//Rows为DataTable的数据行的集合
if (dt.Rows.Count > 0)
{
string code = this.TextBox3.Text;
HttpCookie cookie = Request.Cookies["CheckCode"];
if (code == cookie.Value.ToString())
{
Response.Write("<script type='text/javascript'>alert('ok');</script>");
}
}
else
{
Response.Write("<script type='text/javascript'>alert('error');</script>");
}
//con.Close();//关闭连接
}
catch
{
Response.Write("<script type='text/javascript'>alert('error');</script>");
}
}