我尝试对数据库进行身份验证,以创建登录功能。每次按下按钮时,我都会收到此错误:System.InvalidOperationException:连接未打开。在 MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) 在 MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) 在 MySql.Data.MySqlClient.MySqlCommand.Prepare() 在 start.CheckUserLogin(String username, String password ) 在 c:\Users\RARES\Documents\Visual Studio 2010\WebSites\tem1\start.aspx.cs:第 46 行
请告诉我如何读取数据并检查用户和密码是否与 ThextBox 文本相同。
protected void Button1_Click(object sender, EventArgs e)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
if (CheckUserLogin(Label2.Text, Label3.Text))
{
Response.Redirect("login.aspx");
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public Boolean CheckUserLogin(string username, string password)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
String query = "Select * from users where username= ?userName and password= ?passWord";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.Parameters.Add("?userName", TextBox1.Text);
cmd.Parameters.Add("?passWord", TextBox2.Text);
cmd.Prepare();
MySqlDataReader print = cmd.ExecuteReader();
bool read = print.Read();
if(username.Equals(print.GetString("1")) && password.Equals(print.GetString("2"))) return true;
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
return false;
}