protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True ");
con.Open();
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName'" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
问问题
7625 次
4 回答
1
where username **=**
忘记等号
另外,您打开的连接和使用的连接不同
于 2013-11-02T06:26:51.530 回答
0
在我看来,您在Page_Load
处理程序中打开了与 SQL 服务器的连接。但你不要关闭它。
如果您尝试打开另一个对象,或尝试在已关闭的SqlConnection
对象上执行,您可能会收到错误消息。
一个很好的方法是做这样的事情:
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
//do something here
}
catch (Exception)
{
/*Handle error*/
}
}
于 2013-11-02T06:29:52.240 回答
0
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True");
con.Open();
}
catch
{
//Handles exceptions here
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
try
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName='" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
finally
{
con.Close();
}
}
于 2013-11-02T06:34:38.313 回答
0
如果您为登录编码,那么这里有一个简洁的版本代码,取决于您的标志集,您可以重定向或显示错误的密码信息
bool flagset=false;
SqlDataReader dr;
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select password from TestDemo where userName=@uName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@uName", txtusername.Text);
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows){
while (dr.Read())
{
if(dr[0].ToString()==txtusername.Text)
{ flagset=true; }
}
}dr.Close();
con.Close();
}
}return flagset;
于 2013-11-02T07:16:21.757 回答